Html.BeginRouteForm doesn't generate URL for named route

橙三吉。 提交于 2019-12-11 04:02:01

问题


I am attempting to use Html.BeginRouteForm to generate the action for a form in my ASP.NET MVC app. The route I am targeting is:

//CREATE
routes.MapRoute("map-config-post", "projects/{projectId}/mapconfigs",
    new { controller = controllerName, action = "Create" },
    new { httpMethod = new RestfulHttpMethodConstraint("POST") });

Unit testing and following the route in the app is successful. Now, I would like to create an HTML form with this route is it's URL:

@using (Html.BeginRouteForm("map-config-post", new { projectId = Model.Project.Id }))
{ 
    //form stuff
}

This results in an HTML form with a blank action attribute. Googling around, it seems like this is supposed to work. This is a "New" view, so the current (i.e., postback) route is

projects/1/mapconfigs/new

And I want it to post to

projects/1/mapconfigs

which is what the form action should be.

I can manually make this all happen if I don't use the helpers, but then I lose the nice auto-validation stuff on the client-side.

So, any ideas of what I am doing wrong? Hopefully it's clear what I am trying to do.


回答1:


It seems that the problem comes from your custom RestfulHttpMethodConstraint constraint. Using the default one works perfectly fine:

routes.MapRoute(
    "map-config-post",
    "projects/{projectId}/mapconfigs",
    new { controller = "Home", action = "Create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

and then:

@using (Html.BeginRouteForm("map-config-post", new { projectId = Model.Project.Id }))
{ 
}

generates:

<form action="/projects/123/mapconfigs" method="post">

</form>


来源:https://stackoverflow.com/questions/4810150/html-beginrouteform-doesnt-generate-url-for-named-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!