Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading C# property into JQuery code

I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.

    $(".AspNet-GridView-Normal > td > input").click(function() {

        //Need to access the C# property here

        //Take action here based on the value of the C# property

     });
like image 752
Russ Clark Avatar asked Aug 19 '09 13:08

Russ Clark


2 Answers

This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.

Markup:

<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>

Code Behind:

hfValueINeedToKnow.Value = <some value>;

jQuery:

$("#<%= hfValueINeedToKnow.ClientID %>").val();

You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.

like image 101
Mark Kanof Avatar answered Oct 16 '22 00:10

Mark Kanof


You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:

<script>
$(".AspNet-GridView-Normal > td > input").click(function() {

    var AvailableInstalls = <%= AvailableInstalls %>;

});
</script>
like image 22
Crescent Fresh Avatar answered Oct 15 '22 22:10

Crescent Fresh