I find myself pasting this code over and over on many views that deal with forms.
Is there a simple approach to refactor the following markup from a view in MVC2?
The only changing part is the route for the cancel link (LocalizedSaveButton and LocalizedCancelLink are helper methods I created).
I tried extracting it to a PartialView but I lose the BeginForm functionality. Any suggestions?
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="span-14">
<% Html.EnableClientValidation(); %>
<%using (Html.BeginForm())
{%>
<fieldset>
<legend>Edit Profile</legend>
<%=Html.AntiForgeryToken() %>
<%=Html.EditorForModel() %>
<div class="span-6 prepend-3">
<%=Html.LocalizedSaveButton() %>
<%=Html.LocalizedCancelLink(RoutingHelper.HomeDefault()) %>
</div>
</fieldset>
<%}%>
</div>
You could wrap your code in an Html-Extension like the BeginForm. From your code call the BeginForm on the correct place.
You should return an object that implements IDisposable. In the dispose you call the Dispose of the stored result to BeginForm.
You end up with:
The trick is not to return a string or MvcHtmlString, but directly write the output using:
It would do something like:
and the extension:
Disclaimer: This is untested code.