Html.BeginRouteForm doesn't generate URL for n

2019-07-21 08:17发布

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条回答
淡お忘
2楼-- · 2019-07-21 08:57

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>
查看更多
登录 后发表回答