2013-05-12 140 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