Using Ajax v Forms
I have a table with each row row containing a task. I would like to have a column with links allowing the user to toggle the completed status of the task.
As this is changing data, I only allow the change Action to be called from a Post. I.e. I have an ActionFilter of [AcceptVerbs(HttpVerbs.Post)].
This in turn requires a form in each row of the table. This works, but has an ugly button everywhere.
I think I could achive the data security I am looking for, by doing using an Ajax.ActionLink, and checking in the Action to make sure it is an ajax call.
Currently I have something like
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ToggleToDoItem(int Id, int? page)
{
//update completed status
...
return ToDoItemsPv(null, page);
}
I am looking to change it to public ActionResult ToggleToDoItem(int Id, int? page) { if (HttpContext.Request.IsAjaxRequest()) { //update completed status ...
开发者_JAVA技巧 return ToDoItemsPv(null, page);
}
else
{
return Redirect(some error page);
}
}
The main thing I am trying to achive, is replacing the form buttons with links so it looks better.
Is this safe? Is it good practise?
Thanks
This seems to me to be a little backwards.
My immediate reaction is why are you not using jQuery to do a postback, update the data in the DB, return a flag or whatever and just update that bit of the screen that needs it?
There's no good reason why you can't use jQuery partial postback here and it would do away with having a form for every single item of data.
I would even go so far as to return a PartialView which, with jQuery on success, I would append or replace existing content with.
EDIT
I do partial postbacks like this;
$.post("/Articles/jQueryAddComment", { commentText: commentText, id: id}, function(newCommentListHTML) {
// the newCommentListHTML is a partial view that I return
// and i simply replace the contents of the comment list with
// this new content.
});
My C#;
public ActionResult jQueryAddComment(string commentText, int id)
{
//get data
return PartialView("CommentLisr");
}
You will need to adapt the jQuery stuff so you don't replace the whole lot, or whatever it is you want to replace.
jQuery
There are some cool jQuery commands that you will want to play with.
If you are appending the new partialView then use the (append) keyword. If you are replacing it then simply replace the contents of the bounding div with the new contents.
<div class="BoundingData">
</div>
$('.BoundingData').html(NewHTMLFromPostback);
Ajax.ActionLink includes an option to set the http method so it can do a POST
eg
<%= Ajax.ActionLink(c.Completed ? "Mark uncompleted" : "Mark completed", "ToggleToDoItem", new { Id = c.Id}, new AjaxOptions { UpdateTargetId = "partial", HttpMethod = "POST" })%>
精彩评论