加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 将HTML属性添加到Html.BeginForm()的变体

发布时间:2020-12-16 06:46:59 所属栏目:asp.Net 来源:网络整理
导读:我需要一个ASP.NET MVC Razor页面上的表单.我的偏好是使用以下语法: @using (Html.BeginForm()){} 但是,我需要在表单中添加几个属性.所以我最终得到了以下内容: @using (Html.BeginForm(null,null,FormMethod.Post,new { name = "value" })){} 然而,这具有
我需要一个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,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" }))
{
    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读