2014-01-29 99 views
7

我有控制器名稱:區和動作名稱:Incharges但我想要的網址是這樣(有一些paremeter動作名稱)MVC控制器動作參數爲空

www.example.com/district/incharges/ AAA

www.example.com/district/incharges/bbb

www.example.com/district/incharges/ccc

但是,在調試teamName總是在動作參數返回爲NULL。

路由

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

      routes.MapRoute(
      "DistrictDetails", 
      "District/Incharges/{teamName}", 
      new { controller = "District", action = "Incharges" } 
      ); 

控制器

但是,在調試teamName總是在動作參數返回爲NULL。

public class DistrictController : Controller 
    {  


     public ActionResult Incharges(string teamName) 
     { 
      InchargePresentationVM INPVM = new InchargePresentationVM(); 
      INPVM.InitializePath(teamName, string.Empty); 
      return View("", INPVM); 
     } 
} 

查看

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index About</h2> 

回答

16

具體路線,你必須聲明第一

routes.MapRoute(
      "DistrictDetails", 
      "District/Incharges/{teamName}", 
      new { controller = "District", action = "Incharges", id = UrlParameter.Optional } 

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

感謝您的更新。它的工作正常。 – Velu

+0

永遠受歡迎。 –

+0

記住參數名稱是非常重要的。在上面的情況下,動作中的參數名稱必須與路由規則相同,即Incharges(字符串id),否則將規則更改爲新的{controller =「District」,action =「Incharges」,teamname = UrlParameter.Optional} – learnerplates

1

ASP.NET MVC DefaultModelBinder會嘗試這樣做值的隱式類型轉換,從你的價值提供者,例如。形式,到行動方法參數。如果試圖以一種從價值提供者的參數轉換,它是不是能夠做到這一點,它會賦予null的參數。

關於路由,ASP.NET MVC有轉換優於配置的概念。如果你按照轉換,那麼而不是配置。你可以讓你的默認路由,並始終命名您的控制器,操作方法和參數名稱有你想要的路線。

擁有超過配置,您必須保留默認的HomeController這是應用程序的入口點,然後指定其他控制器如下的約定。這些可以符合你想要的路線名稱。

namespace ConversionOverConfiguration 
    { 

     public class DistrictController: Controller 
     { 
     public ActionResult Incharges(int aaa) 
     { 
      //You implementation here 

      return View(); 
     } 

     } 

    } 
The route will look as below if you have this conversion implementation 
    //Controller/ActionMethod/ActionMethodParameter 
    //District/Incharges/aaa 

這會給你域名的URI:www.example.com/district/incharges/aaa。如果操作方法參數類型是字符串,則域URI是:www.example.com/district/incharges/?aaa =名稱 是一個字符串。那麼你可以保留ASP.NET MVC默認路由

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