.NET MVC The action parameter of an object of type

If I have a simple controller routed as follows:

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

And the action of the Foo controller is as follows:

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

How will the bar be bound? I am debugging and see that this is a string , but I'm not sure if it will always be bound to a string.

Basically, I want the method to accept bool , List<int> and int . I can send a type parameter and make a model of binding myself from the message. (A message is a form message).

Here are my current messages &bar=False or &bar=23 or &bar[0]=24&bar[1]=22 .

I know that I can see the message inside the Foo action method, but I want some input to be the best way to handle this in MVC3

+4
source share
2 answers

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 multiple types. See here

MVC3 ModelBinder for DynamicObject

+3
source

Custom model binding is one of the options that you can apply to your parameter. Your binder can best guess the type (if MVC doesn't get a better hint of context, it will just take a string). However, this will not give you strongly typed parameters; you will have to check and throw. And while it does not really matter ...

Another possibility that will give you strong typing in the actions of your controller is 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; } } 
+2
source

Source: https://habr.com/ru/post/1393801/


All Articles