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 ?
RenderAction(HtmlHelper, String) Invokes the specified child action method and renders the result inline in the parent view. RenderAction(HtmlHelper, String, Object) Invokes the specified child action method using the specified parameters and renders the result inline in the parent view.
The difference between the two is that Html. RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html. Action returns a string with the result.
A render action is a public method on the controller class. You can define a render action method to return any data, but you can only safely use it if it returns an HTML markup string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With