CurlyFro
CurlyFro

Reputation: 1882

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?

Upvotes: 1

Views: 469

Answers (3)

queen3
queen3

Reputation: 15521

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];
}

Upvotes: 2

Daniel Robinson
Daniel Robinson

Reputation: 2245

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".

Upvotes: 2

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

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.

Upvotes: 0

Related Questions