4

I have the JQuery code:

$(document).ready(function() {
    $('.LikeArea').click(function() {
        var num = parseInt(this.html());
        num++;
        elem.html(num);     
    });
});

Now I want to pass the jQuery variable num to Razor so I can update the database with the new value.

dfsq
  • 191,768
  • 25
  • 236
  • 258
Xon
  • 55
  • 1
  • 1
  • 5
  • Possible duplicate of [How to pass a value to razor variable from javascript variable?](https://stackoverflow.com/questions/28317182/how-to-pass-a-value-to-razor-variable-from-javascript-variable) – Michał Perłakowski Jun 20 '17 at 15:23

1 Answers1

9

Razor is a view engine. Not really sure what you mean when you say that you want to pass a jQuery variable to Razor because Razor runs on the server before any javascript. You could use AJAX though to send a request to a server side template:

$(document).ready(function() {
    $('.LikeArea').click(function () {
        var num = parseInt(this.html());
        num++;
        elem.html(num);     
        $.ajax({
            url: '/foo.cshtml',
            type: 'POST',
            data: { num: num },
            success: function(result) {
                // TODO: do something with the result returned by the 
                // foo.cshtml template
            }
        });
    });
});

which would send an AJAX request to the /foo.cshtml template in which you can fetch the variable like this:

@{
    var num = Request["num"];
}
...
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the fast reply. But I'm not really familiar with MVC. I'm using WebMatrix. Can you show me how to get the same result using WebMatrix please? – Xon Jan 29 '12 at 19:30
  • @Xoni, oh sorry, I thought you was using ASP.NET MVC. I have updated my answer to provide an example with WebPages. – Darin Dimitrov Jan 29 '12 at 19:34
  • @DarinDimitrov--I agree with your approach, but do you think the OP may be better off using jQuery's `.post()' instead? It does the same thing, but might be a little more straight-forward. Just my opinion really. – Matt Cashatt Jan 29 '12 at 19:40
  • @MatthewPatrickCashatt, sure the shorthand $.post could have been used in this case. – Darin Dimitrov Jan 29 '12 at 19:41
  • @DarinDimitrov--Then again, if the OP is unfamiliar with jQuery, then using `.ajax()` is going too teach the parts and pieces first which is good for that individual. Anyway, cheers! – Matt Cashatt Jan 29 '12 at 19:44