How to do a partial post in Asp.Net MVC?
I am ne开发者_运维问答w 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?
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');
}
});
}
ASP.Net MVC is not limited to use only one form in the page like Web Form. While Ajax solution is preferred to your scenario, you can also use normal HTTP POST as below;
@using (Html.BeginForm(new { controller = "Comments", action = "Like" })) {
<button type="submit">Like</button>
}
精彩评论