简体   繁体   中英

How to add variable to server-side binding

i have javascript code that looks like this:

$('#lnkPopup').click(function()
{
    var id = $(this).attr('rel');

    var msgCount = '<%= Model.ElementAt('+id+').MailCount %>';
});

<%= Model.ElementAt('+id+').MailCount %> doesn't work.

so how do i add a javascript variable to a serverside query this?

There are two possible ways to answer this question.

1) The short answer is you can't do exactly what you're attempting.

The first thing to understand is that the code between the server tags <% %> is only server side code.

The tag...

<%=

...means the server will generate the output and send the result to the client.

Javascript & jQuery code is client-side code only.

So your javascript / jQuery can not interact directly with the server side code. However, you can generate the client-side code from the server-side.


2) How do we get a value from the client-side code to the server-side?

There are a couple of approaches to this, and it will depend on the style you've chosen for your web application, and the problem at hand.

  • Post or Get to a URL - this could be using performed using AJAX.
  • Generate the javascript / jQuery code you need on the server so you don't need to "post back".
var mailCountTable = {};
<% foreach (var id in Model.Ids) { %>
  elementTable['<%= id $>'] = '<%= Model.ElementAt(id).MailCount %>';
<% } %>

$('#lnkPopup').click(function()
{
    var id = $(this).attr('rel');
    var msgCount = mailCountTable[id];
});

Alternatively you can get your mailCountTable using $.getJSON. Or, with lazy loading:

function getMailCount(id) {
  if (mailCountTable.length == 0)
      $.ajax({async: false, url: '/mailcounttable', format: 'json', 
             success: function(data) { mailCountTable = data; } });
  return mailCountTable[id];
}

Basically, you don't. The server code will execute at the server, long before the javascript executes on teh client.

You would have to make an ajax call back to the server in order for server side code to be aware of javascript values.

Alternatively, you could write a javascript hash table with elements and mail counts using server side code. That function could then look up it's value in that hash table upon execution.

There are many ways to solve this, the key concept to understand is that when javascript is executing, your server code is done, so you better have all your data on the page, or call back to the server with ajax.

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