Referencing jquery variables in C# code (ASP.NET MVC)
How do I refe开发者_如何学Crence a jquery variable in a C# block in the view using ASP.NET MVC?
For example:
$(":input[@name='mydropdown']").change(function () {
var selection = $("#myselection").val();
pop($("#md"), <%= Model.choices[selection] %>);
});
Where the selection that is in my C# block is the same as the selection that is referred to in my jquery.
This is not possible to do. The C# code is executed before the HTML is sent to the user's browser, which is before jQuery gets loaded, which is before the variable selection
has a chance to exist.
There are two approaches to work around this:
- Dump all data that you care from
Model.choices
to a JavaScript variable; your JS code can then access that variable. This is simple and good if your data is not too large in volume. - Have the JS code make an AJAX request to the server to get whatever data it needs by passing the value of
selection
as a query string parameter.
Perhaps try Sharpkit plugin from jquery website:
http://plugins.jquery.com/project/SharpKit
You can't do this because of the browser (client) does not share any memory or state with the server what so ever
i.e.
- the server executes the c# that renders the html and js
- the browser downloads this and interprets it
- the browser executes the javascript (no c#!)
I'd go with Jon's suggestion 1) as it will be more performant by negating the need for another callback to the server.
Long live ASP.NET MVC! :)
精彩评论