2009-06-03 43 views
2

我一直在進入想要爲操作方法提供稍微更直觀或「格式良好」的參數名稱的場景,但是使用默認行爲,這會變得非常痛苦。例如,假設我有一個像GetWidget(int id)這樣的動作參數。如果我希望它是GetWidget(int widgetId),我必須添加一條新路線。當你使用類似於jqGrid的庫時,它的查詢字符串參數使用了糟糕的名字:GetWidgets(int?nodeid,int?n_level)。相反,我想有GetWidgets(int?parentId,int?level)或類似的東西。在ASP.NET MVC中將參數綁定到不同名稱的方法?

那麼,有沒有簡單的東西可以忽略?看起來應該是一件非常簡單的事情,告訴MVC我的「parentId」參數應該綁定到請求中的「nodeid」的值。我想寫一個自定義的動作過濾器來做到這一點,但似乎很明顯,我不相信它不支持開箱即用。

回答

1

使用你自己的,它實現IModelBinder自定義模型粘合劑

3

如果您在URL中使用命名參數,你可以指定該參數的具體名稱到您的控制器的方法,像這樣:

http://mydomain.com/mycontroller/getwidget?parentid=1&level=2 

...並且您不必在參數上匹配路線。

+0

問題是,它是第三部分庫生成查詢字符串參數,它使用醜陋的名稱(如n_level)。我可以編輯源代碼,但我想避免這種情況。 – 2009-06-03 21:34:31

4

根據Rony的答案,使用自定義模型綁定器。這裏是一個例子:

public class BindToAliasAttribute : CustomModelBinderAttribute 
{ 
    private readonly string parameterAlias; 

    public BindToAliasAttribute(string parameterAlias) 
    { 
     this.parameterAlias = parameterAlias; 
    } 

    public override IModelBinder GetBinder() 
    { 
     return new ParameterWithAliasModelBinder(parameterAlias); 
    } 
} 

public class ParameterWithAliasModelBinder : IModelBinder 
{ 
    private readonly string parameterAlias; 

    public ParameterWithAliasModelBinder(string parameterAlias) 
    { 
     this.parameterAlias = parameterAlias; 
    } 

    object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     return controllerContext.RouteData.Values[parameterAlias]; 
    } 
} 

public class UserController : Controller 
{ 
    [HttpGet] 
    public ActionResult Show([BindToAlias("id")] string username) 
    { 
     ... 
    } 
} 
相關問題