MVC action method and pipe in query string parameter
-
02-07-2021 - |
Domanda
I have a call to a get action method with a list of query string parameters being passed to that method. A few of those parameters have a pipe '|' in them. The problem is that I cannot have action method parameters with pipe characters in them. How do I map a piped querystring parameter to a non-piped C# parameter? Or is there some other trick that I don't know about?
Soluzione
You could write a custom model binder. For example let's suppose that you have the following request:
/foo/bar?foos=foo1|foo2|foo3&bar=baz
and you would like to bind this request to the following action:
public ActionResult SomeAction(string[] foos, string bar)
{
...
}
All you have to do is write a custom model binder:
public class PipeSeparatedValuesModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values == null)
{
return Enumerable.Empty<string>();
}
return values.AttemptedValue.Split('|');
}
}
and then:
public ActionResult SomeAction(
[ModelBinder(typeof(PipeSeparatedValuesModelBinder))] string[] foos,
string bar
)
{
...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow