在MVC2中重构表单

时间:2010-09-07 14:08:01

标签: asp.net-mvc asp.net-mvc-2 mvccontrib t4mvc

我发现自己在许多处理表单的视图上一遍又一遍地粘贴这些代码。 是否有一种简单的方法可以从MVC2中的视图重构以下标记? 唯一不断变化的部分是取消链接的路由(LocalizedSaveButton和LocalizedCancelLink是我创建的辅助方法)。 我尝试将其解压缩到PartialView但我失去了BeginForm功能。有什么建议吗?

<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>

2 个答案:

答案 0 :(得分:1)

您可以将代码包装在像BeginForm这样的Html扩展中。从您的代码中调用正确位置的BeginForm。

您应该返回一个实现IDisposable的对象。在dispose中,您将存储结果的Dispose调用为BeginForm。

你最终得到:

<% using (Html.MyBeginForm()) { %>
    <%=Html.LocalizedSaveButton() %> 
    <%=Html.LocalizedCancelLink(RoutingHelper.HomeDefault()) %>   
<% } %>

诀窍不是返回一个字符串或MvcHtmlString,而是使用以下命令直接写输出:

htmlHelper.ViewContext.Writer.Write(....);

它会做类似的事情:

public class MyForm : IDisposable {
    private MvcForm _form;
    private ViewContext _ctx; 

    public MyForm(HtmlHelper html, /* other params */) {
       _form = html.BeginForm();
       _ctx = html.ViewContext;
    }

    public Dispose() {
        _form.Dispose();
        _ctx.Writer.Write("html part 3 => closing tags");
    }
}

和扩展名:

public static MyForm MyBeginForm(this HtmlHelper html /* other params */) {
    html.ViewContext.Writer.Write("html part 1");
    var result = new MyForm(html);
    html.ViewContext.Writer.Write("html part 2");
    return result;
}

免责声明:这是未经测试的代码。

答案 1 :(得分:1)

这是我提出的: 它主要工作,但我无法让Html.EnableClientValidation()与渲染的表单合作。

namespace System.Web.Mvc
{
        public class MyForm : IDisposable
        {
            private bool _disposed;
            private readonly HttpResponseBase _httpResponse;

        public MyForm(HttpResponseBase httpResponse)
        {
            if (httpResponse == null)
            {
                throw new ArgumentNullException("httpResponse");
            }
            _httpResponse = httpResponse;
        }

        public void Dispose()
        {
            Dispose(true /* disposing */);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                _disposed = true;
                _httpResponse.Write("</form>");
            }
        }

        public void EndForm()
        {
            Dispose(true);
        }
    }
}

public static class MyFormExtensions
{
    public static MyForm FormHelper(
        this HtmlHelper htmlHelper, 
        string formAction, 
        FormMethod method, 
        IDictionary<string, object> htmlAttributes, 
        string formLegendTitle)
    {
        TagBuilder tagBuilder = new TagBuilder("form");

        tagBuilder.MergeAttributes(htmlAttributes);

        tagBuilder.MergeAttribute("action", formAction);
        tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
        HttpResponseBase httpResponse = htmlHelper.ViewContext.HttpContext.Response;
        httpResponse.Write(tagBuilder.ToString(TagRenderMode.StartTag));

        return new MyForm(httpResponse);
    }



    public static MyForm MyBeginForm(this HtmlHelper html, string formLegendTitle) {

        string formAction = html.ViewContext.HttpContext.Request.RawUrl;
        var result = FormHelper(html,formAction, FormMethod.Post, null, formLegendTitle );

            html.ViewContext.Writer.Write("<fieldset>");
            html.ViewContext.Writer.Write(String.Format("<legend>{0}</legend>", formLegendTitle));
            html.ViewContext.Writer.Write("<div class=\"span-14\">");
            html.ViewContext.Writer.Write(html.AntiForgeryToken());
            html.ViewContext.Writer.Write(html.EditorForModel());
            html.ViewContext.Writer.Write("<div class=\"span-6 prepend-3 buttons\">");
            html.ViewContext.Writer.Write(html.LocalizedSaveButton());
            html.ViewContext.Writer.Write("</div>");
            html.ViewContext.Writer.Write("</div>");
            html.ViewContext.Writer.Write("</fieldset>");

        return result;

    }

    public static void EndForm(this HtmlHelper htmlHelper)
    {
        HttpResponseBase httpResponse = htmlHelper.ViewContext.HttpContext.Response;
        httpResponse.Write("</form>");
    }
}