2014-01-09 94 views
0

我有一個具有以下作用的控制器的類型:必須有一個字符串值,或者是它實現IRouteConstraint

public ActionResult Post(int pId) 
    { 
     urlPostTitle = "Hello"; 
     pId=23; 
     return RedirectPermanent(Url.Action("PostRedirect", new { pId = pId, postTitle = urlPostTitle })); 
    } 

我的路線爲:

routes.MapRoute("GetPostRedirect", "{pId}/{postTitle}", new { controller = "Blog", action = "PostRedirect", }, new { pId = @"^\d{1,3}$", postTitle = UrlParameter.Optional }); 

但我得到這個錯誤在return RedirectPermanent行:

The constraint entry 'postTitle' on the route with URL '{pId}/{postTitle}' must have a string value or be of a type which implements IRouteConstraint. 

我無法理解的原因錯誤爲urlPostTitle是一個字符串,請幫我解決這個錯誤。

回答

0

看起來你有點混淆。試試這個:

routes.MapRoute(
    "GetPostRedirect", 
    "{pId}/{postTitle}", 
    new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional }, 
    new { pId = @"^\d{1,3}$" }); 

此:

new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional } 

爲每個參數指定默認值,而這一點:

new { pId = @"^\d{1,3}$" } 

被指定哪些規定值的參數的約束被允許承擔。

較新版本的MVC(4及更高版本)實際上使用Named Arguments以使區分更清楚。所以上面的代碼會變成:

routes.MapRoute(
    name: "GetPostRedirect", 
    url: "{pId}/{postTitle}", 
    defaults: new { controller = "Blog", action = "PostRedirect", postTitle = UrlParameter.Optional }, 
    constraints: new { pId = @"^\d{1,3}$" }); 
相關問題