Pass code after variable 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 by keyup and onclick events. So far, I have something like this:

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

but I need:

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

where UserId and ControlId are some identifiers that I get in the code from the query string. I also use jQuery 1.6.4.

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

+5
source share
6 answers

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

That way, you can pass the variables to some model that is passed to the View, and when you have these variables in the 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 that can be accessed from any single js file from the same view file using the variable "myList".

+1
source

I would use data attributes:

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

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

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

Use on instead of bind

As with 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 using a razor (if you use asp.net mvc):

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

or if its web forms:

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

declare the variable as public in the code behind

 public string userId="abc"; 

Client side access

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

Javascript areas are not similar to areas in other languages ​​so if you write

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

he will work

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

-1
source

Is my mydiv class, id or jQuery variable? It looks like you need to do

 $('div.mydiv') or $('div#mydiv') 
-2
source

Source: https://habr.com/ru/post/1438865/


All Articles