Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Ajaxified RenderAction

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 ?

like image 314
xantrus Avatar asked Mar 03 '10 19:03

xantrus


People also ask

What is RenderAction in MVC?

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.

What is the difference between HTML action and HTML RenderAction?

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.

What is action Render?

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.


1 Answers

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.

like image 116
Craig Stuntz Avatar answered Oct 21 '22 16:10

Craig Stuntz