2014-04-22 48 views
0

嘿所有我添加了兩個自定義路線MVC路由與多個參數不工作

routes.MapRoute(
      "ParentCat", 
      "{PCat}/{id}", 
      new { Controller = "Adds", Action = "DetailWanted", PCat = UrlParameter.Optional, id = UrlParameter.Optional }); 

routes.MapRoute(
      "SubCat", 
      "{PCat}/{SCat}/{id}", 
      new { Controller = "Adds", Action = "DetailWanted", PCat = UrlParameter.Optional, SCat = UrlParameter.Optional, id = UrlParameter.Optional }); 

中的url

localhost:2110/Category/addid 

&

localhost:2110/Category/SubCategory/addid 

但調試器直移動和stucks在自定義路由的DetailWanted操作,甚至在我的默認路由

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

不叫

+0

多個可選參數可能不是可能的,但任何一個可以PLZ給出一個解決方案或替代 –

回答

0

我遇到了一個解決方案上

this thing solved my problem

,然後改寫了我的路線爲

routes.MapRoute(
      name: "SubCat", 
      url: "{PCat}/{SCat}/{id}", 
      defaults: new { Controller = "Adds", Action = "Details" });//, id = UrlParameter.Optional PCat = UrlParameter.Optional, SCat = UrlParameter.Optional, 

     routes.MapRoute(
      name: "ParentCat", 
      url: "{PCat}/{id}", 
      defaults: new { Controller = "Adds", Action = "Details" });//,PCat = UrlParameter.Optional,id = UrlParameter.Optional 

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

與控制器代碼

public ActionResult Details(string PCat = null, string SCat = null, int id = 0) 
    { 
     Add add = new Add(); 
     if (PCat == null && SCat == null && id > 0 && id != null) 
     { 
      add = db.Adds.Single(a => a.AddId == id); 
     } 
     if (SCat == null && PCat != null && id > 0 && id != null) 
     { 
      add = db.Adds.Single(a => a.AddId == id && a.Category.CategoryName == PCat); 
     } 
     if (SCat != null && PCat != null && id > 0 && id != null) 
     { 
      add = db.Adds.Single(a => a.AddId == id && a.Category.CategoryName == PCat && a.Category1.CategoryName == SCat); 
     } 
     if (add == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(add); 
    } 

代替

public ActionResult DetailWanted(string PCat=null,string SCat=null, int id=0) 
    {    
     if (PCat == "Adds" || PCat == null) 
     { 
      return RedirectToAction("Index", "Home");     
     } 
     if (id > 0 && id != null) 
     { 
      if (SCat != null && PCat != null) 
      { 
       //return RedirectToAction("Details", "Adds" , new { @id = id }); 
       return Redirect("/Adds/Details/" + id); 
      } 
      else 
      { 
       return RedirectToAction("Details", "Adds" , new { @id = id }); 
      } 
     } 
     else 
     { 
      return RedirectToAction("Index"); 
     } 

     return RedirectToAction("Index", "Home");}