I'm calling a method from the code behind file but for some reason it doesn't execute. This is the method :

 public string getMajorName(int value)
    {
        LibraryArticlesEntities la = new LibraryArticlesEntities();
    //    Label1.Text += "done";
        var majorname = la.Majors.Where(a => a.MajorID == value).Select(a => a.MajorName).SingleOrDefault();
        return majorname;

    }

And I'm calling it from here

<body>
<form id="form1" runat="server">
<div>
    <asp:Label ID="Label2" runat="server" Text='<%#getMajorName(Int32.Parse(Request.QueryString["MajorID"]))%>'></asp:Label>
    <asp:Label ID="Label1" runat="server" Text="label"></asp:Label>
</div>
</form>

Am I missing something here?

Thanks in advance

I am new to MVC coming from web forms and I am struggling getting my head around how you pass parameters into a partial view.

I have the following action result. I want to be able to append a new copy of a partial view to my page when a user clicks a button passing in na new Id. The idea is you get a small section of data but the user can request more which just gets tagged on the end with a different ID value.

Currently this works only when using the routing with an id at the end, but is then static and I cannot add any more.

    public ActionResult GetAllDaysByDate(int Id)
    {
        DateTime theTime = DateTime.ParseExact(Id.ToString(),
                                               "yyyyMMdd",
                                               CultureInfo.InvariantCulture,
                                               DateTimeStyles.None);

        YourDayEntities context = new YourDayEntities();
        var days = context.GetAllDaysByDate(theTime);

        List<Day> day = new List<Day>();

        foreach (var item in days)
        {
            Day d = new Day { DayId = item.DayId, DayDesc = item.DayDesc, DayDate = item.DayDate, ImgUrl = item.ImgUrl };
            day.Add(d);
        }

        return View(day);
    }

I have tried various different methods to pass a param in, such as the following.

@Html.Partial("_GetAllDaysByDatePartial", new ViewDataDictionary(new { Id = 20160101 })) );

But this is throwing an error. Am I going about this all wrong? Thanks in advance.

I have an Rdlc report(asp.net website) with one tablix that related to dsBankBalance and some rows get their values from other datasets for example Sum(Fields!SumStopedCheckes.Value, "dsSumStopedChecks").The problem is when the tablix dataset is empty the tablix become hidden even if the Sum(Fields!SumStopedCheckes.Value, "dsSumStopedChecks") row of tablix return value. I want the structure of tablix remains the same even if the related datasets returns no values. Any Idea?

I should mention I used the visibility property of tablix and I used this expression =iif(CountRows("dsBankBalance") = 0 or CountRows("dsSumStopedChecks") = 0 , false, false) but it didn't work.

I am very new to ASP.NET MVC I've been following this video Create Project & Setup for Responsive Design using Bootstrap and applied what do literally but found a problem in the bootstrap library, which is that Dropdownlist not do dropdown!! which conains 2 items... I think the problem is in JavaScript

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link href="~/Content/bootstrap/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <div>
        @* Header Menu *@

        <div class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <div class="navbar-header"><h1>My first MVC Web Site</h1> </a>
                    <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                </div>
                <div class="navbar-collapse collapse" id="navbar-main">
                    <ul class="nav navbar-nav">
                        <li class="active">
                            <a href="/" style="text-shadow: 0.08em 0.08em 0.3em #ffd800"><h4> Home</h4> </a>
                        </li>
                        <li class="dropdown">
                            <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false" style="text-shadow: 0.08em 0.08em 0.3em #ffd800"><h4>Items </h4><span class="caret"></span></a>
                            <ul class="dropdown-menu">
                                <li><a href="/Campaign"><strong> Item1</strong></a></li>
                                <li>
                                    <a href="/Room"><strong>Item2</strong></a>
                                </li>
                            </ul>
                        </li>
                </div>
            </div>
        </div>

        <div class="container">
            @* Page Header *@
            <div class="page-header" id="banner">

            </div>

            @* Page Body *@
            <div class="page-body">
                <div class="row">
                    <div class="col-xs-12">
                        @RenderBody()
                    </div>
                </div>
            </div>

        </div>

    </div>


    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
    <script src="~/Scripts/bootstrap/bootstrap.min.js"></script>
</body>
</html>

dropdownlist not working

Sorry if duplicated, but I really confused with these javascript. Please help me, if willing.

I have this javascript function that already worked, this function will add thousands separator with commas :

function addCommas(x) {
  //remove commas
  retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;

  //apply formatting
  return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); 
}

And I call this function in the textbox, like this :

 Number Format <asp:TextBox ID="txtPrice" runat="server" onkeyup="this.value=addCommas(this.value);"></asp:TextBox>

The output, looked like this (the separator using commas): "60,000,234"

BUT I want the output, looked like this (the separator using period) : "60.000.234"

Please anyone give me a solution. Thanks

I have shared the view and the viewmodel below. I populated an indented select list (with optgroup) by using foreach loop instead of using some @Html helper. However, I do not know how to assign the selected value from the list to a specific property of the CreateMainEntryViewModel. More specifically, I need to set DiscussionWallId, and TimeFrameId property values based on the selection made in the dropdownlist when the form is submitted with. In this task I am using Ajax.BeginForm() :

@model EcholuMvc.Models.CreateMainEntryViewModel
@using (Ajax.BeginForm("CreateMainEntry", "MainEntry", new AjaxOptions
{     
    UpdateTargetId = "div_MainEntries",
    InsertionMode = InsertionMode.Replace
}))
{       

     @Html.TextBoxFor(m => m.Title, new { placeholder = "Write a brief title...", @class = "form-control input-lg" })

     @Html.TextAreaFor(m => m.Content, new { placeholder = "Type your entry here...", @class = "form-control mainEntryField" })

     <label for="drp_DiscussionWallListForNewMainEntry" style="text-align:right" class="col-sm-3 control-label">Choose the Discussion Wall:</label>

     <select id="drp_DWListForNewMainEntry" class="form-control">
     @{
          foreach (DiscussionWall dw in Model.DiscussionWalls)
          {
               <optgroup label="@dw.WallTitle">
               foreach (TimeFrame tf in dw.TimeFrames)
               {
                  <option data-dw="@dw.WallId" data-tf="@tf.TimeFrameId">@tf.TimeFrameName</option>
               }              
                </optgroup>
         }
     }
     </select>

    <button type="submit" id="btn_SubmitNewPost">Post</button>                           

}

This is the viewmodel:

public class CreateMainEntryViewModel
{

    public string Title { get; set; }

    public string Content { get; set; }

    public Boolean IsAnonymous { get; set; }

    public int DiscussionWallId { get; set; }

    public int TimeFrameId { get; set; }

    public CreateMainEntryViewModel(List<DiscussionWall> walls)
    {
        DiscussionWalls = walls;
    }

    public List< DiscussionWall> DiscussionWalls { get; set; }
}

I appreciate any help!

Right now I am doing this to get the information I need:

In my base controller:

    public int roleId { get; private set; }
    public int userId { get; private set; }

    public void setUserAndRole()
    {
        ClaimsIdentity claimsIdentity;
        var httpContext = HttpContext.Current;
        claimsIdentity = httpContext.User.Identity as ClaimsIdentity;
        roleId = Int32.Parse(claimsIdentity.FindFirst("RoleId").Value);
        userId = Int32.Parse(User.Identity.GetUserId());
    }

In my controller methods:

    public async Task<IHttpActionResult> getTest(int examId, int userTestId, int retrieve)
    {
        setUserAndRole();

I wanted the roleId and userId to be available and populated in the constructor of my class but from what I understand the constructor fires before authorization information is available.

Can someone tell me how I could do this with an Action Filter? Ideally I would like the Action Filter to be at the controller level but if not then could it be done at the method level.

I am hoping for some good advice and suggestions. Thank you

tried looking at other examples on this and am a bit confused. I have 2 web servers that are load balanced and a sql server box (sql 2012). my cube is created on the sql server box (i see it in management studio). when i try to access via my asp.net page i receive the above error.

now, i see the msolap110.dll in C:\Program Files (x86)\Microsoft Analysis Services\AS OLEDB\110 on the sql box. do i need to do something permission wise with the dll or something? do i need to install analysis services on the web server? is there a specific port or something (doubtful as sql is running fine).

connection string is as follows: "Provider=msolap;Data Source=;Initial Catalog=AutoOLAPAW;Cube Name=SampleCube;"

going to try to force to use MSOLAP.5 but waiting on a republish from our security/deployment group.

this all works fine in dev but my (more secured/stripped down) prod/qa is where i'm seeing the issue. using iis7 on both.

I am exploring the use of Sections to create optional content in my site's layout, as explained quite neatly in ScottGu's article here:

http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor

However, what I'm trying to do is add a sidebar to the views related to a specific controller, where the sidebar contains static information relevant to the controller. The data won't be tied to the model - it'll just be some links to external pages, and some static 'helper' text.

I don't want the Sidebar on every page / view - just on some views (in my case, it's the view related to a specific controller).

What I don't want to do is have to declare the same Section and content for each view that needs this. I was trying to find some way of creating a 'shared section' - that I could reference neatly in the views that require it, and pass back to the _Layout when the View is returned by the controller.

Partial Views seemed to be the way forward with this:

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

But I'm not sure if this is the right way to go about this, or if there's more succinct way to achieve what I'm aiming for.

I have been searching for answers on this, but as ever with this sort of thing, I am 100% sure I am not using the correct terminology in my search attempts for this - so apologies if this is duplicate post, basic stuff, or has already been answered elsewhere.

Any pointers on this - even if it's just to give me some direction on the terms to search on - would be welcome !

I've not provided any example code here, but could possibly knock something up if it helps articulate things.

Cheers

Im trying to make a typical webshop, got everything worked out so far, but I got this following issue: How do I replace duplicate database-value in a List to quantity instead, and list them into ListView? E.g. if I add two of same product into my cart, I want to be able to show quantity instead showing two of same product in the cart-list.

PS: Im listing my results in ListView.

(Form_Load for cart):

using (eShopEntities db = new eShopEntities()){

            var list = new List<Product>(db.Products.ToList());

            var listFilter = new List<Product>(); 

            foreach (var id in list)
            {
                foreach (var Sessions in SessionData)//got selected products stored in sessions
                {
                    if (id.ID == Sessions)
                    {

                        listFilter.Add(id); //Add all selected products(via session)
                    }
                }
            }

            int TotSum = 0;
            foreach (var sum in listFilter)
            {
                TotSum = TotSum + sum.Price;

            }

            cartListView.DataSource = listFilter; cartListView.DataBind();

            lblSum.Text = TotSum.ToString();


           }

Right now, everything is listed in aspx. But Im not sure how to replace duplicated into quantities from listFilter AND send the quanties-data along with the result from listFilter into cartListWiev togheter.

My Product table(SQL): ID(PK), Name, ImagePath, Price, and CatergoryID(FK)

Thanks

i have a grid view in Asp.net. i want to generate button for specific rows. Like i have a column named as "Status". If status is "Accept" a button should be generated in that particular row. column

I have some doubles that I want to format as strings so that they look like this:

   $ 123.00
($ 3,231.99)
     $ 0.82

So basically I need to get the positive doubles to print with a single trailing space. Here is the string formatted:

Value1.ToString("$ #,0.00 ;($ #,0.00);$ 0.00 ");

However, when they are being printed, on the web page the trailing space is not included. What am I missing?

I created a EditorFor template for DateTime types. If there's no value (0001-01-01) then use the current date. The problem is that it displays the date and time. I could change DateTime.Now.ToString() to DateTime.Now.ToString("yyyy-MM-dd") but is there a way to enforce it in the model with a annotation like[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]`?

DateTime.cshtml

@model DateTime

@{
    var validationAttributes = Html.GetUnobtrusiveValidationAttributes("");

    <div class="input-control text full-size" data-role="datepicker">
        @Html.TextBox("", ViewData.Model.Year > 1 ? ViewData.Model.Date.ToString() : DateTime.Now.ToString(), new RouteValueDictionary(validationAttributes))
        <button class="button"><span class="mif-calendar"></span></button>
    </div>
}

MyViewModel.cs

namespace MyProject.ViewModels
{
    public class NewRequestViewModel
    {
        public NewRequestViewModel()
        {

        }

        public int ID { get; set; }

        [Required]
        [StringLength(255)]
        public string Title { get; set; }

        [Required]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime StartDate { get; set; }
    }
}

MyView.cshtml

@Html.EditorFor(model => model.StartDate)

i have one web application with signalR, and that is upload on server with IIS8.

now what i want is if form same signalr i want chat 1. web - android application 2. web - IOS application 3. android - IOS application

with same port, it is possible ? if yes then how?

please help me out on this.

Thanks, Jimmy Darji

Hi all how can I access the data list rows inside jquery, this is how my data list looks when data got binded. I will have multiple lists and in each list I will have some items associated.

Assume I have listA and listB

In listA and listB I can have some items as common saved to his list. What I need is when I selected an item from listA and wanted to removed that if that item exists in ListB it should get remove

My html

<asp:datalist id="datalist1" Runat="server" Width="100%">
 <HeaderTemplate>
 <table>
 <tr>
 <td>Fav</td>
<td width="135"></td>
<td width="100" align="left"></td>
<td width="300" align="center"></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Table runat="server" ID="tbl1">
<asp:TableRow runat="server" ID="row">
<asp:TableCell runat="server" width="150" ID="cell1" VerticalAlign="Top" HorizontalAlign="Left">
<asp:Label ID="label1" runat="server" Text='<%# DataBinder.Eval( Container.DataItem , "myItem") %>'>
</asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:table>

enter image description here

I tried creating Web Service file inside ASP.NET MVC Web App project but it's not working. Can anyone tell me what' the reason behind it? This is my first time creating this kind of program. Thanks for the help.

WEB SERVICE - code

EmployeeService.asmx

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Demo
{
    /// <summary>
    /// Summary description for EmployeeService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {

        [WebMethod]
        public Employee GetEmployeeById(int employeeId)
        {
            Employee employee = new Employee();

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter parameter = new SqlParameter();
                parameter.ParameterName = "@Id";
                parameter.Value = employeeId;

                cmd.Parameters.Add(parameter);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    employee.ID = Convert.ToInt32(rdr["Id"]);
                    employee.Name = rdr["Name"].ToString();
                    employee.Gender = rdr["Gender"].ToString();
                    employee.Salary = Convert.ToInt32(rdr["Salary"]);
                }
            }

            return employee;
        }
    }
}

When i run this code, this page will appear. enter image description here

This is the result when I clicked the INVOKE button.

enter image description here

Recently I have upgraded my sql server from 2012 to sql server 2014 .

Now all my applications connected to this server can't instantiate the connection .

i debug the code and I get the following exception :

'Connection.ServerVersion' threw an exception of type System.IvalidOperationException


My connection string like this :

 <add name="sql_r" connectionString="Data Source=172.XX.XX.X;Initial Catalog=Attendance;User ID=ll_web;password=XXXXXXXXXXX;" providerName="System.Data.SqlClient"/>

I have running a PHP code inside my website on IIS server by iframeas following:

<body>
    <h1>My Trusted Authentication Server</h1>

    <?php
        //Some PHP code
    ?>

    <iframe src="<?= $server?>/<?= $ticket ?>/<?= $view ?>" width="800" height="800"></iframe>

 </body>

I have configured my web.config file:

<system.webServer>
    <handlers>
      <add name="php_cgi" path="*.html" verb="GET,HEAD,POST" modules="FastCgiModule" scriptProcessor="C:\Program Files (x86)\PHP\php-cgi.exe" resourceType="File" requireAccess="Script" />
    </handlers>
  </system.webServer>

and create php_cgi module in HanleMapping on IIS server.

But when I build and run the website, I still got the error:

HTTP Error 500.0 - Internal Server Error The page cannot be displayed because an internal server error has occurred.

Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the Web site or application. The authenticated user does not have permission to use this DLL. The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.

Things you can try: Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. Check the event logs to see if any additional information was logged. Verify the permissions for the DLL. Install the .NET Extensibility feature if the request is mapped to a managed handler. Check the failed request tracing logs for additional information about this error. For more information, click here.

Detailed Error Information: Module FastCgiModule Notification
ExecuteRequestHandler Handler php_cgi Error Code 0x80070585 Requested URL http://localhost:56279/index.html Physical Path
C:\Users\V0917950\Documents\Visual Studio 2015\WebSites\WebSite1\index.html Logon Method Anonymous Logon User Anonymous Request Tracing Directory
C:\Users\V0917950\Documents\IISExpress\TraceLogFiles\WEBSITE1(1)

How should I do to prevent this problem? Thank you very much for your help!

I have the following call to post a subscribe to a Mailchimp List but it returns unauthorized. I have the API key, list and username stored in the web.config which i have triple checked.

using (var wc = new System.Net.WebClient())
{
    string parameters = string.Concat("email_address=", email, "&amp;status=", "subscribed"),
           url = "https://us12.api.mailchimp.com/3.0/lists/" + ConfigurationManager.AppSettings["MailChimp.ListId"] + "/members";

    wc.Headers.Add("Content-Type", "application/json");

    wc.Credentials = new NetworkCredential("", ConfigurationManager.AppSettings["MailChimp.ApiKey"]);

    string result = wc.UploadString(url, parameters);
}

We want to switch our ASP.NET MVC application from Azure Cloud Service to Azure App Service (web app). The application is currently using WIF as its identity framework, and as it is running in a farm configuration, we configured a custom SessionSecurityTokenHandler which encrypts the session cookie using a certificate (thus the cookie can be decrypted by all instances of the web farm).

We could provision this certificate in the Cloud Service scenario using the csdef/cscfg files and the built-in Azure certificate store associated with the Cloud Service, but there is no such thing with Azure App Services (unless I missed something).

Is there any way to configure a certificate in the App Service? Should we fall back to another mechanism to encrypt the session cookie, such as a shared machine key? The machine key is not an ideal solution as it forces us to leave some configuration out of source control to avoid leaking the key.

I want to get data in android (client) application from C# (Server) app. I have only option to do that is Soap Web Service. But my problem is that i want to communicate both application at back end for authentication using PAP or CHAP. My server can disconnect connection at any time. How i can do this with web service. Or i have to use web service after socket connection? Please help me. I have successfully connected both applications by web service and android gets results from server.