Reputation: 175
How do I reference 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.
Upvotes: 2
Views: 1788
Reputation: 1887
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.
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! :)
Upvotes: 0
Reputation: 2730
Perhaps try Sharpkit plugin from jquery website:
http://plugins.jquery.com/project/SharpKit
Upvotes: 0
Reputation: 437336
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:
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.selection
as a query string parameter.Upvotes: 6