简体   繁体   中英

Pass code behind variable value to jQuery function

I am not an expert in jQuery and I am trying to pass some variable values from C# to my function called on keyup and onclick events. So far I have something like this:

$('mydiv').bind('keyup click', function(event) {}

but what I need should be:

$('mydiv').bind('keyup click', function(event, UserId, ControlId) {}

, where UserId and ControlId are some ids I am getting in code behind from the query string. I am also using jQuery 1.6.4.

How can I do this, preferably without using hidden input fields? Thank you.

I would use data-attributes:

$('mydiv').data({ userId: <%= UserId %>, ControllId: <%= ControllId %> })

then you can access those data in the on click event:

$('mydiv').on('click', function(event) {
  var userId = $(this).data('userId');
  var ControlId = $(this).data('ControlId');
});

Use on instead of bind

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

Passing values from the server to the client with razor (if youre using asp.net mvc):

$('mydiv').on('keyup click', function(event, @UserId, @ControlId) {}

or if its webforms:

$('mydiv')
    .on('keyup click', function(event, <%= UserId %>, <%= ControllId %>) {}

declare the variable as public in code behind

public string userId="abc"; 

Access it on client side

var uid='<%=userId %>';
$('mydiv').bind('keyup click', function(event, uid, ControlId) {}

A js file cannot directly access C# objects so you need to do something like below. Even if you want to write complete jQuery code in your view file, you can still follow same approach.

So you can pass variables in some Model which is passed to View and once you have those variables in Model you can do something like below:

 <script type="text/javascript">
    var myList= @Html.Raw(Json.Encode(@Model.UsersList));      
</script>

So now you have a json object which can be accessed by any individual js file as well with in same view file with the help of variable "myList".

Javascript scopes are not like scopes in other languages so if you write

var UserId = 5; 
var ControlId = 5;

$('mydiv').bind('keyup click', function(event) 
{
  alert( UserId );  
});

it will work

check out http://jsfiddle.net/FgYTL/1/

Is my mydiv a class, id or a jQuery variable? Looks like you need to do

$('div.mydiv') or $('div#mydiv') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM