Html.BeginForm() with only form Id is not generating correct action url

时光怂恿深爱的人放手 提交于 2019-12-05 11:15:56

When you are trying to generate a route, such as with BeginForm, MVC will do its best to include things that you might need.

If you're at domain.com/Home/Index/b9f88f80-f31f-4144-9066-55384c9f1cfc and you use the code that you have provided than the form will be generated with the action, controller and route values as it finds them.

controller / action / id
/Home      / Index  / b9f88f80-f31f-4144-9066-55384c9f1cfc

One way to get around this is to force id to be nothing (such as an empty string).

Observe:

@using (Html.BeginForm(null, null, new { @id = string.Empty },
    FormMethod.Post, new { @id = "Id" }))
{

}

The new { @id = string.Empty } is an anonymous object that represents the route values.

Change @id to id.

 @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "MyForm1" }))    
    {
        <input id="submit" type="submit" value="Search" />
    }

Because of in System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like bellowed:-

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

Means like this : Html.BeginForm( string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes)

So, it worked for me in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "trainingForm" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!