If I want a specific cshtml file (asp.net mvc 4) to have access to specific functionality in javascript or jquery, how should I enable to do it in Visual Studio 2013?

All cshtml file should not have access to all functionality in javascript or jquery.


ASP.NET MVC4 razor helper cannot pass type parameters to generic methods. To fix this, probably best way is to add non-generic get method with signature

public static string Get(Type entityType)

How to add this wrapper so it calls generic Get method in this class. Should reflection used or is there better way?

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
  public sealed class LocalizableDisplayNameAttributeI :   DisplayNameAttribute

    public LocalizableDisplayNameAttributeI(string displayName) : base(displayName) { }

    public override string DisplayName
            return global::Res.Translate(base.DisplayName);

    public static string Get<TEntity>()
        foreach (LocalizableDisplayNameAttributeI attrib in
            typeof(TEntity).GetCustomAttributes(typeof(LocalizableDisplayNameAttributeI), true))
            return attrib.DisplayName;
        return typeof(TEntity).Name;

How to use Url.Action() in Razor helper from App_Code folder ?

I tried according to Why I cant use Html.RenderPartial in razor helper view File in App_Code Folder?

@using System.Web.Mvc.Html
@helper Tabel(System.Web.Mvc.HtmlHelper html)
    @Html.Raw(Url.Action("Index", "Home"))

but got compile error

CS0103: The name 'Url' does not exist in the current context

ASP.NET MVC4 and jquery are used.

I'm trying to customise ASP.NET Identity 3 so that it uses integer keys:

public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }

public sealed class ApplicationRole : IdentityRole<int>
  public ApplicationRole() { }
  public ApplicationRole(string name) { Name = name; }

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, int>
  public ApplicationUserStore(ApplicationDbContext context) : base(context) { }

public class ApplicationRoleStore : RoleStore<ApplicationRole, ApplicationDbContext, int>
  public ApplicationRoleStore(ApplicationDbContext context) : base(context) { }

public class ApplicationUser : IdentityUser<int>

public sealed class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
  private static bool _created;

  public ApplicationDbContext()
    // Create the database and schema if it doesn't exist
    if (!_created) {
      _created = true;

This compiles okay, but then throws a runtime error:


GenericArguments[0], 'TeacherPlanner.Models.ApplicationUser', on 'Microsoft.AspNet.Identity.EntityFramework.UserStore`4[TUser,TRole,TContext,TKey]' violates the constraint of type parameter 'TUser'.

ApplicationUser is precisely an IdentityUser<int>. Isn't this what it's looking for?

For a class project we have to use ASP.net with VB code to do a user login, I've followed the steps pretty closely, but it seems I'm missing something. when

Dim strSQL As String = "SELECT * FROM [" & TABLE_NAME & "]" 


Dim dv As DataView = ds.Tables(TABLE_NAME).DefaultView 

come up "TABLE_NAME" is underlined as an undeclared object. According to my understanding this should simply pass in the name of the table I am using? I am rather confused as to what I am doing wrong here. Any help would be appreciated, here is the entire code page. I am sure I am simply making some amatuer mistake.

Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient

Partial Class index
    Inherits System.Web.UI.Page
    Dim con As New SqlConnection("Server = tcp:kw0ythb209.database.windows.net,1433;Database=dynamicSite;User ID=nolanzippel@gmail.com;Password=haruhi23;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;")
    Dim da As New SqlDataAdapter()
    Dim cmd As New SqlCommand()
    Dim ds As New DataSet()

    Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
        Dim strSQL As String = "SELECT * FROM [" & TABLE_NAME & "]"
            da.SelectCommand = New SqlCommand(strSQL, con)
            da.Fill(ds, "dynamicSite")
        Catch ex As Exception
        End Try
        ' Get the dataview from the table
        ' alternative to: ds.Tables(0)
        ' A dataview allows sorting
        Dim dv As DataView = ds.Tables(TABLE_NAME).DefaultView

        dv.Sort = "name"
        Dim searchString As String = txtUser.Text
        Dim myIndex As Integer = dv.Find(searchString)

        If myIndex <> -1 Then

            dv.Sort = "pass"
            Dim searchString2 As String = txtPass.Text
            Dim myIndex2 As Integer = dv.Find(searchString)

            If myIndex2 <> -1 Then

            End If


        End If
    End Sub

I have two pages, on one page i use jquery post functon to post a url with several parameters through api, but when i click on that button(on which it applied), it generate a popup with text -5 Phone one is required

So basically, I am trying to return a set of values to a GridView, which doesn't meet any of the values within an array. However, upon attempting I am getting the error of

LINQ to Entities does not recognize the method 'Int32 ToInt32(Boolean)' method, and this method cannot be translated into a store expression.

Here is my code:

        public List<Room> getAvailRoom()
        //Sessions from Default Page
        DateTime checkedIn = Convert.ToDateTime(System.Web.HttpContext.Current.Session["checkIn"]);
        DateTime checkedOut = Convert.ToDateTime(System.Web.HttpContext.Current.Session["checkOut"]);

        //retrieves all the bookings which happen between two dates
        var booking = (from b in context.Booking
                         where b.departureDate >= checkedIn && b.arrivalDate <= checkedOut
                         select b);

        //Counts how many rooms are booked during those dates
        int countRooms = booking.Count();

        int[] bookings = new int[countRooms];
        foreach (var booktypes in booking)

                for (int i = 0; i < countRooms; i++)
                    //Addings the RoomIds to the array
                    bookings[i] = booktypes.RoomId;

        //Returns values that does not equal to any roomIds within the bookings array.
        return (from b in context.Room
                where b.roomId != Convert.ToInt32(bookings.Any())
                select b).ToList();

Any ideas what I am doing incorrectly?

Recently I download the visual studuio 2015 RC and I want to implement the reset password in my app. I wrote some line for do this:

ApplicationDbContext context = new ApplicationDbContext();
ApplicationUser _user = context.Users.First(u => u.UserName == UserName);
var resetResult = await UserManager.ResetPasswordAsync(_user, ResetToken, NewPassword);

and I create a token in the previos function as follow :

ApplicationDbContext context = new ApplicationDbContext();
ApplicationUser _user = context.Users.First(u => u.UserName == UserName);
var ResetToken = await UserManager.GeneratePasswordResetTokenAsync(_user);

But an error raised on the line of ResetPasswordAsync :

The instance of entity type 'IX.InfoBay.Framework.ApplicationUser' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.

The connection and other settings are ok because I can do registering and updating the users.

(I'm sorry if my English is not good)

I has a Ajax ModalPopupExtender as below code:

 <cc1:ModalPopupExtender runat="server" ID="modalFormPopup" OkControlID="btnOKFake" ClientIDMode="Static"
        Drag="true" TargetControlID="btnFake" BehaviorID="modalFormPopupBID" Enabled="true"
        BackgroundCssClass="ModalPopupBG" PopupControlID="pnFake">
<asp:Button runat="server" ID="btnFake" Text="Show Popup" Style="display: none" />
<asp:Button runat="server" ID="btnOKFake" Text="Show Popup" Style="display: none" />
<asp:Panel runat="server" ID="pnFake" Style="display: none"></asp:Panel>

And I'll process it in my javascript code as below.

var modal = $find("modalFormPopupBID");

My problem is: - When I use

<cc1:ToolkitScriptManager ID="abc123" runat="server">

in my content page and don't use ToolkitScriptManager in Master Page, it's ok. - But when I use ToolkitScriptManager in my Master Page as

<body style="min-height: 700px;">
<form runat="server" id="Form1">
   <cc1:ToolkitScriptManager runat="server" ID="ToolkitScriptManager1">

and use ScriptManagerProxy in Content Page as

<asp:ScriptManagerProxy runat="server" ID="ScriptManagerProxy1"></asp:ScriptManagerProxy>

everything is good but i can't execute var modal = $find("modalFormPopupBID"); it's always return null, that mean can't find my Ajax ModalPopupExtended. I spend many time to fix it, but it still return null. Whether it is bug of Ajax toolkit ?

Thanks for read my long post, I hope i'll find answer to continue my project. - Khanh Nguyen Huy - From Vietnam.

I trying to send parameters by GET request to my web api method like this:


headers: Content-Type: application/json; charset=utf-8

And my api method is:

public void someaction(ModelParams p)
    //do some action

And "ModelParams" is:

public class ModelParams
        public string val1{ get; set; }
        public string val2{ get; set; }

I get the model = null in service. Why?

Localizable displayname attribute is defined as class below. How to create razon helper which returs it from entity type ?

I tried

@helper Menyy<TEntity>()

but got parser error

Parser Error Message: Expected a "(" after the helper name.


    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class LocalizableDisplayNameAttributeI : DisplayNameAttribute

        public LocalizableDisplayNameAttributeI(string displayName) : base(displayName) { }

        public override string DisplayName
                return global::Res.Translate(base.DisplayName);

        public static string Get<TEntity>()
            foreach (LocalizableDisplayNameAttributeI attrib in
                typeof(TEntity).GetCustomAttributes(typeof(LocalizableDisplayNameAttributeI), true))
                return attrib.DisplayName;
            return typeof(TEntity).Name;

ASP.NET MVC4, jquery, and C# are used.

I have followed some of the instructions to create a new LinkButton at runtime with an event trigger and add an event handler for the LinkButton generated. I have no idea why the new LinkButton does not trigger the event added to it. Anyone please guide/correct me.

This is what I have right now.


<form id="myForm" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">


 <table class="mel-table" style="text-align: center" runat="server" id="mytab1">

            <td>Case Number :</td>

            <asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>



   <asp:Button OnClick="btnOK1_Click" ID="btnOK1" runat="server" Text="Save" />




Protected Overloads Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Session("tablecontent") IsNot Nothing Then
        mytab1 = CType(Session("tablecontent"), HtmlTable)
    End If
End Sub

Public Function checking() As Boolean

        Dim caseNo As Double
                caseNo = Convert.ToDouble((caseNumber.Text).Trim())
            Catch ex As Exception
            caseNo = 0
            End Try

        Dim r As New HtmlTableRow
        Dim c0 As New HtmlTableCell

        Dim but As New LinkButton
        but.ID = caseNo 
        but.Text = caseNo.ToString() 
        AddHandler but.Click, AddressOf LinkButton1_Click

        Session("tablecontent") = mytab1
End Function

Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)

    'My Code here

End Sub

Protected Sub btnOK1_Click(sender As Object, e As EventArgs)

    If (checking()) Then

        ScriptManager.RegisterStartupScript(Page, Page.GetType, "Alert", "<script type='text/javascript'>alert('Success');</script>", False)

    End If

End Sub

I have a webapi project with several controllers and actions each returning complex types(class with lot of list of classes). The issue is if the value of null for a string , I want the json to have "" instead of the letter null.

I tried overriding a JSONConvertor and adding in global.asax, but it doesnt seem to work as the value I get in WriteJson is of type the object and PopulateandIgnore does not work.

Is there a way to do this ?

Simple question - How do I assign a string ViewData value to HTML input; alternatively, how to I write a C# razor input textbox with the following attributes:

<input type="text" id="priceText2" onkeyup="placeValues()" value=@ViewData["price"]>

The example above does not process multi-word values because it does not add the quotes to the value (e.g., value = my multi-word value). Adding quotes to the value string do not produce the desired result, and neither do inline single quotes. I get the feeling the answer is a razor textbox, but I am new to razor and under a time crunch at work.

If I add a razor textbox, are there any implications on javascript assignments (e.g., document.getElementById("bla").value = "...";) or retrievals (e.g., var myVar = document.getElementById("bla").value;)? This is a HTML5 mobile written on Xamarin, so it does not include jQuery...

This question already has an answer here:

i have a ashx page(handler) which upload image in server.How i can How can I get a variable fname in js.Unfortunately, all my attempts were unsuccessful

public class fileuploadHandler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        if (context.Request.Files.Count > 0)
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
                HttpPostedFile file = files[i];
                string fname = context.Server.MapPath("~/img/" + "111"+file.FileName);
        context.Response.ContentType = "text/plain";
        context.Response.Write("File(s) Uploaded Successfully!");

and js

$(document).ready(function () {
        $("#Buttonsave").click(function (evt) {
            var fileUpload = $("#FileUpload1").get(0);
            var files = fileUpload.files;

            var data = new FormData();
            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);

            var options = {};
            options.url = "fileuploadHandler.ashx";
            options.type = "POST";
            options.data = data;
            options.contentType = false;
            options.processData = false;
            options.success = function (result) { alert(result); };
            options.error = function (err) { alert(err.statusText); };


        var fname=.....//Here to receive a variable 


I am porting a windows desktop application to an ASP.NET MVC application. I have a bunch of tables in the database that I am able to create controllers with to generate views and it works fine. I want to create a page to display all the names that have a certain column that is set to false. Because there is no table that stores this data I have to manually query for the result using linq. So what I have done is ignored the creation of the model and created the controller.

private raceEntities db = new raceEntities();

    // GET: Registrants
    public ActionResult Index()
        var registrants = (from per in db.people
                          join personorgrole in db.personorganizationroles on per.PersonID equals personorgrole.PersonID
                          join personeve in db.personevents on personorgrole.PersonOrganizationRoleID equals personeve.PersonOrganizationRoleID
                          join eventcla in db.eventclasses on personeve.RaceEventID equals eventcla.RaceEventID
                          join racecla in db.raceclasses on eventcla.RaceClassID equals racecla.RaceClassID
                          join personeventcla in db.personeventclasses on eventcla.EventClassID equals personeventcla.EventClassID
                          where personorgrole.PersonID == 90946
                          select new { per.FirstName, per.LastName }).ToList();
        ViewBag.Res = registrants;

        return View();

and in the view i have this code

@model IEnumerable<IDFWebApp.Controllers.Custom.peopleController>
    ViewBag.Title = "Index";

    @foreach (var r in ViewBag.Res)

Currently this query is for testing purposes to see if the data will show on the page, but it doesn't display the names.

After trying, browsing, testing for hours I still don't get it. Here is the problem:

I've started the project with the ASP.NET Web Site Razor v3 template in Visual Studio Community 2013. Why the heck this code causes the latest (desktop) browsers NOT to load the images. As you see, the HTML string is set to the variable and then I try to output it as HTML code:

@{ var q = "<img src=\"~/Images/Arrow-Back-iconL.png\" alt=\"galerija puščica levo\" id=\"puscicaL_0\" class=\"puscica puscical\" style=\"opacity:1\" />";
 @(new HtmlString(q))

But this code of course enables images to load:

<img src="~/Images/Arrow-Back-iconL.png" alt="galerija puščica levo" id="puscicaL_0" class="puscica puscical" style="opacity:1" />

I have Website in my localhost (IIS) on Windows 8.1, I can access it from:

It binded to "All Unassigned" and Port 80 and Localhost.

But I can't access this website from another PC (windows 7) in same network.

Please notice that:

  • Both are connected to same wireless modem
  • I have Eset SmartSecurity on both of PCes and firewall are disabled.
  • I can ping both in cmd like:
  • In Windows 7 PC port is bonded (I check it with netstat -na and result is: TCP LISTENING)
  • In Windows 7 PC Telnet 80 connected correctly
  • In Windows 7 Pc also I installed IIS 7
  • Security Permission of website folder

I'm really confused and don't know what to do!!!

What difference between node.js non-blocking model and ASP.NET MVC non-blocking async/await with Tasks ? i meant they successfully solving the same problem in the same way or i missed something ? I think other framework have had the same solution before node ?

I have seen examples like this

public IHttpActionResult GetProduct(int id)
    Product item = repository.Get(id);
    if (item == null)
        throw new HttpResponseException(HttpStatusCode.NotFound);
    return Ok(item);

But I have also imagine this is an option

public IHttpActionResult GetProduct(int id)
    Product item = repository.Get(id);
    if (item == null)
        return NotFound();
    return Ok(item);

Is there an advantage to throwing an exception or simply returning a NotFound (IHttpActionResult instance)?

I know there are stages in the response / request pipeline where either of these results can be handled, like this for the first example

public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute 
    public override void OnException(HttpActionExecutedContext context)
        if (context.Exception is NotFoundException)
            // Do some custom stuff here ...
            context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);


    new ProductStore.NotFoundExceptionFilterAttribute());

Question rebuild.

I have a html table:

<div class="form-group">
    @Html.Label("Lista pytan:", new { @class = "col-md-2 control-label" })
    <table id="questionTable" border="0">
        <tbody id="questionTableBody">

Which is builded dynamically via javascript AddRow() function called onclick:

function addRow(table, value)
        var tab = document.getElementById(table);
        var rowCount = tab.rows.length;
        var row = tab.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var lp = document.createElement("label");
        lp.name = "lblLp[]";
        lp.className = "col-md-2 control-label";
        lp.textContent = "" + (rowCount + 1);
        var cell2 = row.insertCell(1);
        var element1 = document.createElement("label");
        element1.name = "lbl[]";
        element1.className = "col-md-2 control-label";
        element1.textContent = document.getElementById(value).value;
        var cell3 = row.insertCell(2);
        var element2 = document.createElement("input");
        element2.type = "button";
        element2.name = "btn[]";
        element2.value = "Usun";
        element2.className = "btn btn-default";
        element2.addEventListener('click', function () {                
            deleteRow(table, row.rowIndex);

Based on this table i want to create a model right before calling

public ActionResult Add(AddQuestionnaireModel model) 

in my controller.

My model looks like this:

public class AddQuestionnaireModel
    public QuestionnaireServiceReference.Questionnaire Questionnaire {get;set;}

    public AddQuestionnaireModel()
        Questionnaire = new QuestionnaireServiceReference.Questionnaire();

And Questionnaire is an object generated form EntityFramework:

public partial class Questionnaire
    public Questionnaire()
        this.Question = new HashSet<Question>();

    public long questionnaire_id { get; set; }
    public string name { get; set; }

    public virtual ICollection<Question> Question { get; set; }

Most important thing is that Questionnaire contain list of objects. How to via Ajax or Javascript fill a Model in my View?

I have add onclick funkction to my button submit button, named: fillQuestionnaire().

Can you help me build my fillQuestionnaire() javascript funkction? (or ajax if u have other ideas)