Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a partial post in Asp.Net MVC?

I am new to asp.net mvc.

I want to create a site that allow the visitor to do a partial post such as allowing visitors to press a like button to vote a comment.

How to do this in asp.net mvc?

like image 952
xport Avatar asked Dec 28 '22 01:12

xport


1 Answers

You can implement this using Ajax, the browser will send a post "behind the scenes" so to say, without redirecting the user. The server will return data in JSON format.

On the server: Create a new Controller CommentsController and add a Action Like:

[Authorize] /*optional*/
public JsonResult Like(int id)
{
    //validate that the id paramater
    //Insert/Update the database
    return Json(new {result = true});
}

In your view, simply use the jQuery Ajax methods:

function likeComment(id) {
    $.post('<%=Url.Action("Like", "Comments")%>/' + id, function(data){
        //Execute on response from server
        if(data.result) {
            alert('Comment liked');
        } else {
            alert('Comment not liked');
        }
    });
}
like image 200
The Scrum Meister Avatar answered Dec 30 '22 14:12

The Scrum Meister