2013-05-12 143 views
11

我想让我的页面发布到我的Web API控制器,而不是我的Area/Controller/Action。这是我到目前为止,我已经尝试使用这两种Html.BeginForm和Ajax.Begin形式:Html.BeginForm路由到Web Api

@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" })) 

但我不能让任何张贴到根即http://domain/api/Standing,而是后两者的面积即http://domain/Areaname/api/Standing 。我如何让它正确发布?

更新:下面是我对相关区域的路线:

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 }); 
} 

而且我的Web API路线:

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

config.Routes.MapHttpRoute(
    "DefaultApiWithAction", 
    "api/{controller}/{action}/{season}", 
    new { id = RouteParameter.Optional } 
); 
+0

请发表您的'routes' – haim770 2013-05-12 19:01:00

回答

9

你可以明确地告诉链接通过包括张贴到根斜杠:

@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" })) 
+0

感谢,对Ajax.BeginForm工作,但Html.BeginForm没有,所以我Ajax.BeginForm – user517406 2013-05-13 14:37:42

+0

去不得不删除第一个/从“/ API /人大常委会”在Html.BeginForm中。 Mvc似乎在默认情况下添加了一个,所以不然我会得到// api /站点 – Karsten 2015-05-26 19:26:37

7

您需要使用作为Web API路由的链接生成,始终取决于路由名称。还请确保提供如下路线值httproute

@using (Html.BeginRouteForm("DefaultApi", new { controller="Entries", httproute="true" })) 
+0

这实际上帮了我。正在寻找这个很长一段时间。 – 2017-12-02 16:34:11