【问题标题】:How to add ID property to Html.BeginForm() in asp.net mvc?如何在 asp.net mvc 中向 Html.BeginForm() 添加 ID 属性?
【发布时间】:2011-02-20 17:29:09
【问题描述】:

我想使用 jquery 验证我的表单,但到目前为止它还没有 ID 属性,如何将它添加到 asp.net mvc 中的表单中?我正在使用这个...

<% using (Html.BeginForm()) {%>

我的 jquery 验证器插件采用了这个,

var validator = $("#signupform").validate({

现在我想给 id 作为signupform...任何建议...

【问题讨论】:

  • 好问题,与jquery无关

标签: jquery asp.net-mvc forms


【解决方案1】:

这应该会添加 id。

ASP.NET MVC 5 及更低版本:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
   { } %>

ASP.NET Core:您可以use tag helpers in forms 避免设置 id 的奇怪语法。

<form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>

【讨论】:

  • 为什么 action 和 controller 都为空? lz能解释一下吗?
  • 我不知道你想在哪里发布表格,所以我把它们设为空。
  • 同时将动作和控制器设置为 null 可以让您不必对它们进行硬编码。如果您的表单位于局部视图中,并且该局部视图用于创建和编辑等多个视图中,这将非常有用。
  • 在哪里可以找到所有 html 助手的 API 或文档?例如,在哪里可以找到参数代表什么?
  • @Zapnologica 看看这个msdn.microsoft.com/en-us/library/dd460542%28v=vs.108%29.aspx。 htmlAttributes 参数由一个包含名称/值对的对象组成。新的 { id = "myid", @class="myclass" }
【解决方案2】:

我在我的项目中添加了一些代码,这样更方便。

HtmlExtensions.cs:

namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId)
        {
            return htmlHelper.BeginForm(null, null, FormMethod.Post, new { id = formId });
        }

        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId, FormMethod method)
        {
            return htmlHelper.BeginForm(null, null, method, new { id = formId });
        }
    }
}

MySignupForm.cshtml:

@using (Html.BeginForm("signupform")) 
{
    @* Some fields *@
}

【讨论】:

    【解决方案3】:

    System.Web.Mvc.Html 中(在 System.Web.Mvc.dll 中)开始表单的定义如下:- Details

    BeginForm ( this HtmlHelper htmlHelper, string actionName, string
    controllerName、对象 routeValues、FormMethod 方法、对象 html属性)

    意味着你应该像这样使用:

    Html.BeginForm(string actionName, string controllerName,object routeValues、FormMethod 方法、对象 htmlAttributes)

    所以,它在 MVC 4 中工作

    @using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
        new { @id = "signupform" }))
    {
        <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
        <input type="submit" value="Create" id="btnSubmit" />
    }
    

    【讨论】:

      【解决方案4】:

      可能有点晚了,但在我的情况下,我不得不将 id 放在第二个匿名对象中。 这是因为第一个是路由值,即返回 URL。

      @using (Html.BeginForm("Login", "Account", new {  ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))
      

      希望这可以帮助某人:)

      【讨论】:

        猜你喜欢
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 2013-07-22
        • 1970-01-01
        相关资源
        最近更新 更多