Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass JQuery variables to Razor?

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.

like image 330
Xon Avatar asked Jan 18 '23 15:01

Xon


1 Answers

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"];
}
...
like image 157
Darin Dimitrov Avatar answered Jan 26 '23 02:01

Darin Dimitrov