views:

227

answers:

1

I am happy with what the RenderAction() function does. However, I'd like to ajaxify the loading and storing of data in the partially rendered action, so that everything happens in one page.

Imagine the following case: I have an article details view where there's an "Add comment" link beneath the content of the article. When it's clicked, a comment form would appear beneath the content of the post. The user should be able to fill the comment box, and send the data without refreshing the whole view, just the partially rendered action. Also the view must provide for several comments to be added in the same session (several AJAX calls to RenderAction());

Which is the best way to achieve that ?

+4  A: 

Action:

[HttpGet]
public ActionResult AddComment()
{
    return PartialView(); // presumes partial view is called "AddComment" and needs no model
                          // you know what to do otherwise.
}

View:

<input type="button" value="Add Comment" onclick="addComment()" />

JavaScript:

function addComment() {
    $("#comments").append("<div></div>").load("/ControllerName/AddComment");
}

That's the basics. You can make this as complicated as you like.

Craig Stuntz
What about submitting the comments data? Will that happen "inside" the article view, without refreshing the page?
To submit the comments data, just `POST` a form, synchronously or asynchronously. You could have one form per comment, if you want, if you put it in your partial. If you don't want the page to refresh, then `POST` the form asynchronously and update the page (remove the editor and add a `div` with the comment) in JavaScript.
Craig Stuntz