How to add ID property to Html.BeginForm() in asp.net mvc?
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>
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 *@
}
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" />
}
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 :)