2012-05-10 15 views
1

我有一個帶有可選「id」參數的頁面路由。定義像這樣:似乎無法檢查RouteData的可選參數

 routes.MapPageRoute(null, 
      "projects/{operation}/{id}", 
      "~/Projects/ProjectWizard.aspx", 
      true, 
      new RouteValueDictionary(new 
      { 
       operation = "new", 
       id = UrlParameter.Optional 
      }), 
      new RouteValueDictionary(new 
      { 
       operation = @"new|edit", 
       id = @"\d*" 
      }) 
     ); 

路由工作正常,但是當我到達的頁面,如果我沒有包括可選的「ID」參數,然後嘗試轉換爲整數時,我的代碼失敗。

 var operation = RouteData.Values["operation"].ToString(); 
     var projectId = RouteData.Values.ContainsKey("id") ? Convert.ToInt32(RouteData.Values["id"]) : 0; 

這個偉大的工程,只要我傳遞一個ID在這樣的路線:

http://webapp/projects/edit/123 

projectId等於123就像是應該的。但是,如果我不包括ID:

http://webapp/projects/new 

路線轉到頁罰款,但我得到這個錯誤:

Unable to cast object of type 'System.Web.Mvc.UrlParameter' to type 'System.IConvertible'.


它應該是無法找到的關鍵路由數據值,然後分配一個零到projectId,但它不。我一直嘗試不同的方法來檢查「id」路由值爲空,但它似乎並不那麼喜歡。任何幫助深表感謝。

回答

2

如果你在這裏處理MVC控制器操作和MapRoute,那會很好。

我會在你的情況做的是簡單地設置默認的缺省值代替UrlParameter.Optional你的ID,那麼:



routes.MapPageRoute(null, 
    "projects/{operation}/{id}", 
    "~/Projects/ProjectWizard.aspx", 
    true, 
    new RouteValueDictionary(new 
    { 
     operation = "new", 
     id = "0" 
    }), 
    new RouteValueDictionary(new 
    { 
     operation = @"new|edit", 
     id = @"\d*" 
    }) 
); 

然後簡單地看了你的ID如下:


var operation = RouteData.Values["operation"].ToString(); 
var projectId = int.Parse(RouteData.Values["id"].ToString());