How to add ID property to Html.BeginForm() in asp.net mvc?

后端 未结 4 1125
慢半拍i
慢半拍i 2020-12-12 23:03

I want to validate my form using jquery but it doesn\'t have an ID property as of now how to add it to the form in asp.net mvc? I am using this...



        
相关标签:
4条回答
  • 2020-12-12 23:35

    This should get the id added.

    ASP.NET MVC 5 and lower:

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

    ASP.NET Core: You can use tag helpers in forms to avoid the odd syntax for setting the id.

    <form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>
    
    0 讨论(0)
  • 2020-12-12 23:40

    May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.

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

    Hope this can help somebody :)

    0 讨论(0)
  • 2020-12-12 23:41

    In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

    BeginForm ( this HtmlHelper htmlHelper, string actionName, string
    controllerName, object routeValues, FormMethod method, object htmlAttributes)

    Means you should use like this :

    Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

    So, it worked in 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" />
    }
    
    0 讨论(0)
  • 2020-12-12 23:56

    I've added some code to my project, so it's more convenient.

    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 *@
    }
    
    0 讨论(0)
提交回复
热议问题