Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeginRouteForm doesn't work with API routes?

I have a form I'm trying to create with relatively simple code:

@using (Ajax.BeginRouteForm("DefaultApi", new { controller = "persons" }, new AjaxOptions {HttpMethod = "post", OnSuccess = "someSuccess"}))}
{
    @Html.TextBoxFor(m => m.Name)
}

I have a PersonsController, which is an ApiController, and I have the following route in WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

But the BeginRouteForm call returns no action. The resulting HTML:

<form action="" data-ajax="true" data-ajax-method="post" data-ajax-success="someSuccess" id="form0" method="post">
</form>

As you can see, the action is empty. It's not complaining it can't find the route (which it would if it couldn't), so what's going on? I've even tried providing an empty id in the routeValues object, but that doesn't work either (though it shouldn't be required since id is optional).

What am I missing here? Can you not use BeginRouteForm with routes added via MapHttpRoute? The behavior is the same with both Html.BeginRouteForm and Ajax.BeginRouteForm (as it should be, they have the same base). Obviously I'd expect the action to come back '/api/persons' in this case.

like image 203
Matt Holmes Avatar asked Nov 13 '22 05:11

Matt Holmes


1 Answers

Having MVC 5 and Web API 2.2 the following markup in a view worked for me:

@using (Ajax.BeginRouteForm("DefaultApi",
        new { controller = "User", HttpRoute = "true" },
        new AjaxOptions { HttpMethod = "POST", OnFailure = "onFailure", OnSuccess = "onSuccess" }))
{
}
like image 55
abatishchev Avatar answered Nov 15 '22 13:11

abatishchev