.NET MVC Action parameter of type object

前端 未结 2 1796
遥遥无期
遥遥无期 2021-01-19 17:15

If I have a simple controller routed as follows:

context.MapRoute(
            \"Default\",
            \"{controller}/{action}\",
            new { controll         


        
相关标签:
2条回答
  • 2021-01-19 18:00

    A custom model binder is one option, which you could apply to your parameter. Your binder could do best guess at the type (unless MVC gets a better hint from the context, it will just assume string). However, that won't give you strongly typed parameters; you'd have to test and cast. And while that's no big deal...

    Another possibility which would give you strong typing in your controller actions would be to create your own filter attribute to help MVC figure out which method to use.

    [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 讨论(0)
  • 2021-01-19 18:07

    In this case I would probably create a custom ModelBinder:

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

    then maybe use a dynamic object to allow for multiple types. See here

    MVC3 ModelBinder for DynamicObject

    0 讨论(0)
提交回复
热议问题