Carl
Carl

Reputation: 175

Referencing jquery variables in C# code (ASP.NET MVC)

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

Answers (3)

Paul Carroll
Paul Carroll

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.

  • 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! :)

Upvotes: 0

Greg Oks
Greg Oks

Reputation: 2730

Perhaps try Sharpkit plugin from jquery website:

http://plugins.jquery.com/project/SharpKit

Upvotes: 0

Jon
Jon

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:

  1. 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.
  2. 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.

Upvotes: 6

Related Questions