簡體   English   中英

將HTML屬性添加到Html.BeginForm()的變化

[英]Variation on Adding HTML Attributes to Html.BeginForm()

我需要一個ASP.NET MVC Razor頁面上的表單。 我的偏好是使用以下語法:

@using (Html.BeginForm())
{
}

但是,我需要在表單中添加幾個屬性。 所以我最終得到了以下內容:

@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "value" }))
{
}

然而,這具有不希望的副作用。 如果此頁面的請求中存在查詢參數,則第一個表單會在提交表單時傳遞它們。 但是,第二個版本沒有。

我真的不知道為什么BeginForm()不支持屬性,但有沒有一種直接的方法來向BeginForm()添加屬性,並在提交for時仍傳遞任何查詢參數?

編輯:

在研究之后,似乎最好的解決方案是這樣的:

<form action="@Request.RawUrl" method="post" name="value">
</form>

但是,使用此語法時,將禁用客戶端驗證。 在沒有更復雜和可能不可靠的結構的情況下,似乎沒有很好的解決方案。

確實如此,但我會使用自定義幫助程序來保留用於客戶端驗證的表單上下文:

public static class FormExtensions
{
    private static object _lastFormNumKey = new object();

    public static IDisposable BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
        return htmlHelper.FormHelper(rawUrl, FormMethod.Post, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    private static int IncrementFormCount(IDictionary items)
    {
        object obj2 = items[_lastFormNumKey];
        int num = (obj2 != null) ? (((int)obj2) + 1) : 0;
        items[_lastFormNumKey] = num;
        return num;
    }

    private static string DefaultFormIdGenerator(this HtmlHelper htmlhelper)
    {
        int num = IncrementFormCount(htmlhelper.ViewContext.HttpContext.Items);
        return string.Format(CultureInfo.InvariantCulture, "form{0}", new object[] { num });
    }

    private static IDisposable FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
    {
        var builder = new TagBuilder("form");
        builder.MergeAttributes<string, object>(htmlAttributes);
        builder.MergeAttribute("action", formAction);
        builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
        bool flag = htmlHelper.ViewContext.ClientValidationEnabled && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;
        if (flag)
        {
            builder.GenerateId(htmlHelper.DefaultFormIdGenerator());
        }
        htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
        var form = new MvcForm(htmlHelper.ViewContext);
        if (flag)
        {
            htmlHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];
        }
        return form;
    }
}

可以像這樣使用:

@using (Html.BeginForm(htmlAttributes: new { name = "value" }))
{
    ...
}

我有類似的問題,這里是快速解決方案(它適用於MVC4)。

聲明擴展方法:

public static MvcForm BeginForm(this HtmlHelper helper, object htmlAttributes)
{
        return helper.BeginForm(helper.ViewContext.RouteData.Values["Action"].ToString(),
                                helper.ViewContext.RouteData.Values["Controller"].ToString(), 
                                FormMethod.Post, htmlAttributes);
}

並在您的頁面中使用它:

@using (Html.BeginForm(htmlAttributes: new {@class="form-horizontal"})) 
{
...
}

對源代碼的小修改:

http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/FormExtensions.cs

public static MvcForm BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
{
   // generates <form action="{current url}" method="post">...</form>
   string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
   return FormHelper(htmlHelper, formAction, FormMethod.Post, new RouteValueDictionary(htmlAttributes));
}

private static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
   TagBuilder tagBuilder = new TagBuilder("form");
   tagBuilder.MergeAttributes(htmlAttributes);
   // action is implicitly generated, so htmlAttributes take precedence.
   tagBuilder.MergeAttribute("action", formAction);
   // method is an explicit parameter, so it takes precedence over the htmlAttributes.
   tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);

   bool traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled
                                       && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;

   if (traditionalJavascriptEnabled)
   {
       // forms must have an ID for client validation
       tagBuilder.GenerateId(htmlHelper.ViewContext.FormIdGenerator());
   }

   htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
   MvcForm theForm = new MvcForm(htmlHelper.ViewContext);

   if (traditionalJavascriptEnabled)
   {
       htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
   }

   return theForm;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM