2012-01-30 82 views
4

如果我有一個簡單的控制器路由如下:.NET MVC Action參數

context.MapRoute(
      "Default", 
      "{controller}/{action}", 
      new { controller = "Base", action = "Foo"} 
     ); 

而且控制器美孚操作如下:

[HttpPost] 
public ActionResult Foo(object bar) { ... } 

如何bar的約束?我調試過,看到它是一個string,但我不確定它是否總是被編組到一個字符串。

基本上我想要的方法接受bool,List<int>int。我可以發送一個類型參數,並從模塊中綁定我自己的模型。 (該帖子是表單帖子)。

這裏是我當前的帖子&bar=False&bar=23&bar[0]=24&bar[1]=22

我知道我可以看看富action方法裏面的職位,但我想在最好的辦法一些輸入MVC3

+3

它不叫封送 - 其所謂的模型在這方面結合。 – 2012-01-30 16:40:27

+2

爲什麼你使用'object'作爲你的所有參數? – gdoron 2012-01-30 16:43:54

+0

剛剛開始的MVC3和C#,已經在JAX-B的編組/解組世界工作了很長一段時間。 – 2012-01-30 16:44:27

回答

2

處理這種自定義的模型綁定是一個選項,你可以應用到您的參數。你的綁定器可以在類型上做出最好的猜測(除非MVC從上下文中獲得更好的提示,它只會假設字符串)。但是,這不會給你強烈的類型參數;你必須測試和施放。雖然這沒什麼大不了的......

另一種可能會讓你在你的控制器動作中強類型的方法是創建你自己的過濾器屬性來幫助MVC找出使用哪種方法。

[ActionName("SomeMethod"), MatchesParam("value", typeof(int))] 
public ActionResult SomeMethodInt(int value) 
{ 
    // etc 
} 

[ActionName("SomeMethod"), MatchesParam("value", typeof(bool))] 
public ActionResult SomeMethodBool(bool value) 
{ 
    // etc 
} 

[ActionName("SomeMethod"), MatchesParam("value", typeof(List<int>))] 
public ActionResult SomeMethodList(List<int> value) 
{ 
    // etc 
} 


public class MatchesParamAttribute : ActionMethodSelectorAttribute 
{ 
    public string Name { get; private set; } 
    public Type Type { get; private set; } 

    public MatchesParamAttribute(string name, Type type) 
    { Name = name; Type = type; } 

    public override bool IsValidForRequest(ControllerContext context, MethodInfo info) 
    { 
      var val = context.Request[Name]; 

       if (val == null) return false; 

      // test type conversion here; if you can convert val to this.Type, return true; 

      return false; 
    } 
} 
+0

+1這些匹配參數似乎工作正常。由於我將在多個地方使用它,我認爲自定義模型聯編程序更合適。 – 2012-01-30 17:04:17

+0

如果你開始使用'ActionName'屬性,你就失去了應用程序的靈活性。 – gdoron 2012-01-30 17:04:46

+0

@gdoron如何失去靈活性?我不同意。 – HackedByChinese 2012-01-30 17:06:15

相關問題