How to pass JQuery variables to Razor?

2020-02-14 07:02发布

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.

1条回答
倾城 Initia
2楼-- · 2020-02-14 07:38

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"];
}
...
查看更多
登录 后发表回答