2014-05-08 73 views
1

我已經定義自定義路由路由到特定的URL從jQuery的負載

  routes.MapRoute(
       name: "ListRoute", 
       url: "List/{id}", 
       defaults: new { controller = "List", action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional } 
      ); 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional } 
      ); 

,並試圖通過jQuery

$('#dvPartialFeatured').load("@Url.Action("DetailList", "List")"); 

這裏載入我的部分頁面是我在ListController控制器:

public ActionResult Index(string id) 
     { 

      return View(); 
     } 

public PartialViewResult DetailList(int id, int type) 
     { 
      var objSearchModels = new SearchModels() 
      { 
       SubCategory = id, 
       Type = type 
      }; 
      return PartialView("~/Views/ProductListing/_PartialProductListing.cshtml", ProductListingService.PopulateSearchList(objSearchModels)); 
     } 

但它重定向到Index,我甚至試過用

$('#dvPartialFeatured').load("@Url.HttpRouteUrl("Default", new { Controller = "List", Action = "DetailList" })", {id:1, type:2}); 

然而,當我刪除自定義路線ListRoute它做工精細

+0

您的鏈接不包含'type'屬性('id'可以省略,因爲它在路由中是可選的),因此它與方法的簽名不匹配,因此您將被重定向到默認值。 –

+0

我添加類型作爲可選的,但仍然是結果相同 – brykneval

+0

不需要''action =「DetailList」'''而不是''action =「Index」'' –

回答

1

我嘗試了一下在您的代碼測試應用程序,這個網址似乎擊中DetailList行動正確參數綁定和我一直都相同:

/List/DetailList/1?type=2 

這是我試過的示例應用程序的download link

1

你不需要在你的路由中包含一個類型參數(因爲沒有它的段,你不提供它的默認值,大多數操作可能不需要它),所以你可以定義它們如:

routes.MapRoute(
    name: "ListRoute", 
    url: "List/{id}", 
    defaults: new { controller = "List", action = "Index", id = UrlParameter.Optional } 
); 

routes.MapRoute(    
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 

根據這個定義,如果你想針對你的列表控制器的DetailList方法,您需要提供ID和類型參數(因爲它們是在控制器方法的不可爲空的參數)。

但是,如果您想在List控制器中定位Index方法,則不需要提供id參數。這是因爲它是在路徑可選的,並且聲明爲在控制器方法的字符串(所以這將是空,如果被叫沒有ID)

例如:

  • @Url.Action("DetailList", "List", new {id = 1, type = 2})生成URL /List/DetailList/1?type=2,這將在ListControllerDetailList操作中結束。

  • @Url.Action("Index", "List", new { id = 1 })將生成的URL /List/1(使用ListRoute路線),這將在ListControllerIndex行動結束。

  • @Url.Action("Index", "List")將生成的URL /List(使用ListRoute路線),這將在ListControllerIndex動作結束,與ID爲空值。

希望它有幫助!

+0

我剛剛獲得並放大,所以現在使用Html.Raw和它現在好了,反正謝謝 – brykneval