14

I am trying to get my page to post to my Web API controller, rather than my Area/Controller/Action. Here is what I have so far, I have tried using both Html.BeginForm and Ajax.Begin Form :

@using (Ajax.BeginForm("", "", null, new AjaxOptions { HttpMethod = "POST", Url = "api/Standing" }, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

@using (Html.BeginForm("", "api/Standing", FormMethod.Post, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

But I cannot get either to post to the root ie http://domain/api/Standing, instead both post to the Area ie http://domain/Areaname/api/Standing. How do I get it to post correctly?

Update: Here are my routes for the relevant area :

public override string AreaName
{
    get
    {
        return "Areaname";
    }
}

public override void RegisterArea(AreaRegistrationContext context)
{
    string defaultLocale = "en-US";

    context.MapRoute(
        "Areaname_default",
        "{languageCode}/Areaname/{controller}/{action}/{id}",
        new { languageCode = defaultLocale, controller = "Main", action = "Index", id = UrlParameter.Optional });

    context.MapRoute(
        "History",
        "{languageCode}/Areaname/{controller}/{action}/{year}",
        new { controller = "History", action = "Season", year = UrlParameter.Optional });
}

And my Web API routes :

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

config.Routes.MapHttpRoute(
    "DefaultApiWithAction",
    "api/{controller}/{action}/{season}",
    new { id = RouteParameter.Optional }
);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
user517406
  • 13,623
  • 29
  • 80
  • 120

2 Answers2

13

You can explicitly tell the links to post to the root by including the leading slash:

@using (Ajax.BeginForm("", "", null, new AjaxOptions { HttpMethod = "POST", Url = "/api/Standing" }, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

@using (Html.BeginForm("", "/api/Standing", FormMethod.Post, new { id = "frmStandingAdd", name = "frmStandingAdd" }))
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • Thanks, the Ajax.BeginForm works, but the Html.BeginForm does not, so I went with Ajax.BeginForm – user517406 May 13 '13 at 14:37
  • Had to remove the first / from "/api/Standing" in Html.BeginForm. Mvc seems to be adding one by default, so otherwise I would get //api/standing – Karsten May 26 '15 at 19:26
8

You would need to use BeginRouteForm as link generation to Web API routes always depends on the route name. Also make sure to supply the route value called httproute as below.

@using (Html.BeginRouteForm("DefaultApi", new { controller="Entries", httproute="true" }))
Kiran
  • 56,921
  • 15
  • 176
  • 161