April 25, 2010
Rendering Inline using HTML.Action in MVC 2.0
Posted by Brian Mains under ASP.NET MVC, WebNo Comments
Html.Action is a method method that injects a response from the server directly into the UI. For instance, a controller can have two action methods, then inject the response directly into the UI from the other controller. Take a look at the sample form below:
<p>
Main Action
</p>
<% Html.BeginForm(); %>
<div>
Name: <%= Html.TextBox(“IndexName”) %>
</div>
<div>
Value: <%= Html.TextBox(“IndexValue”) %>
</div>
<input type=”submit” value=”save” />
<% Html.EndForm(); %>
<%= Html.Action(“Custom”, new { title = “Test Title” }) %>
The custom action gets invoked and injected into the main view. Any parameters that get passed to the action method get passed as a routing parameter, as shown here (a title property). Below is the sample controller methods that return the view to inject.
[HttpGet, ChildActionOnly]
public ActionResult Custom()
{
return PartialView();
}
[HttpPost]
public ActionResult Custom(FormCollection form)
{
return PartialView();
}
[HttpGet]
public ActionResult Index()
{
return View();
}
The main view calls the Index method to get the response, that view calls the Custom action method. Note the ChildActionOnly attribute; this designates that the action method can only be used within a main view. The Custom action method returns a PartialView to insert a partial response into the UI, rather than including a whole view. The child view below is what gets injected. This partial view has its own form to receive a post to the server.
<p>
Custom Action
</p>
<% Html.BeginForm(“Custom”, “RenderingActions”); %>
<div>
Name: <%= Html.TextBox(“CustomName”) %>
</div>
<div>
Value: <%= Html.TextBox(“CustomValue”)%>
</div>
<input type=”submit” value=”save” />
<% Html.EndForm(); %>
And that’s it, we can have multiple actions linked to one view, and they all can post back to their own action methods and such. I plan to cover some of the other details at a later date.