在 MVC2 中重构表单

发布于 2024-09-17 20:53:43 字数 845 浏览 10 评论 0原文

我发现自己一遍又一遍地将这段代码粘贴到许多处理表单的视图上。 是否有一种简单的方法可以从 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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独行侠 2024-09-24 20:53:43

您可以将代码包装在 HTML 扩展中,例如 BeginForm。从您的代码中在正确的位置调用 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;
}

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

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:

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

The trick is not to return a string or MvcHtmlString, but directly write the output using:

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

It would do something like:

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");
    }
}

and the extension:

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

Disclaimer: This is untested code.

江南烟雨〆相思醉 2024-09-24 20:53:43

这是我想出的:
它大部分有效,但我无法让 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>");
    }
}

Here is what I came up with:
It mostly works but I haven't been able to get the Html.EnableClientValidation() to cooperate with the rendered form.

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>");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文