对象类型的.NET MVC Action参数



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

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

控制器Foo的动作如下:

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

bar将如何绑定?我已经调试过,看到它是一个string,但我不确定它是否总是被编组为字符串。

基本上,我希望该方法接受boolList<int>int。我可以从帖子中发送一个类型参数并自己进行模型绑定。(该帖子是一个表单帖子)。

以下是我目前的帖子&bar=False&bar=23&bar[0]=24&bar[1]=22

我知道我可以在Foo操作方法中查看帖子,但我想在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<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;
     }
}

最新更新