0
我有一个调用get操作方法与查询字符串参数列表传递给该方法。其中一些参数有一个管道'|'在他们中。问题是我无法在其中使用管道字符的操作方法参数。如何将管道查询字符串参数映射到非管道C#参数?或者还有其他一些我不知道的技巧吗?MVC操作方法和查询字符串参数管道
我有一个调用get操作方法与查询字符串参数列表传递给该方法。其中一些参数有一个管道'|'在他们中。问题是我无法在其中使用管道字符的操作方法参数。如何将管道查询字符串参数映射到非管道C#参数?或者还有其他一些我不知道的技巧吗?MVC操作方法和查询字符串参数管道
您可以编写自定义模型联编程序。例如,让我们假设你有以下要求:
/foo/bar?foos=foo1|foo2|foo3&bar=baz
,你要绑定这个请求以下行动:
public ActionResult SomeAction(string[] foos, string bar)
{
...
}
所有你所要做的就是写一个自定义的模型绑定:
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('|');
}
}
然后:
public ActionResult SomeAction(
[ModelBinder(typeof(PipeSeparatedValuesModelBinder))] string[] foos,
string bar
)
{
...
}