2016-01-17 401 views
0

我已經在MVC中創建了具有不同路由名稱的多個路由。從javascript函數MVC路由配置:具有不同路由名稱的多個路由

routes.MapRoute(
    name: "PostDetails", 
    url: "Ad/{id}/{item}", 
    defaults: new { controller = "Home", action = "Post" } 
); 

我打電話路由重定向到這條路線

var url = '@Url.RouteUrl("PostDetails", new { id = "_id_", item = "_name_" })';  
url = url.replace("_id_", id).replace("_name_", name); 
window.location.href = url; 

這是給了一個錯誤與404

+0

此腳本在視圖中還是在外部'js'文件中? –

+0

html中生成的url是什麼? – ramiramilu

+0

@StephenMuecke這就像
function postDetails(id,name){ var url ='@ Url.RouteUrl(「PostDetails」,new {id =「_id_」,item =「_name_」})'; url = url.replace(「_ id_」,id).replace(「_ name_」,name); window.location.href = url; } –

回答

1

您必須在默認路徑之前添加您的路線RouteConfig like:

public static void RegisterRoutes(RouteCollection routes) 
{ 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
     routes.MapRoute(
      name: "PostDetails", 
      url: "Ad/{id}/{item}", 
      defaults: new { controller = "Home", action = "Post" } 
     ); 
     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
}