类型为object的.NET MVC Action参数

如果我有一个简单的控制器路由如下:

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

并且控制器Foo动作如下:

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

bar怎么样? 我已经调试并看到它是一个string ,但我不确定它是否总是被编组为一个字符串。

基本上我想让方法接受boolListint 。 我可以发送一个类型参数并从post中自己进行模型绑定。 (该post是一个表格post)。

这是我当前的post&bar=False&bar=23&bar[0]=24&bar[1]=22

我知道我可以看一下Foo动作方法里面的post,但是我想要一些关于在MVC3中处理这个问题的最佳方法的输入

在这种情况下,我可能会创建一个自定义的ModelBinder:

http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/

然后可能使用动态对象来允许多种类型。 看这里

用于DynamicObject的MVC3 ModelBinder

自定义模型绑定器是一个选项,您可以将其应用于参数。 您的绑定器可以最好地猜测类型(除非MVC从上下文获得更好的提示,它将只假设字符串)。 但是,这不会给你强类型参数; 你必须测试和演员。 虽然这没什么大不了的……

另一种可以强制键入控制器动作的可能性是创建自己的filter属性,以帮助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))] public ActionResult SomeMethodList(List 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; } }