【问题标题】:MVC action method and pipe in query string parameter查询字符串参数中的 MVC 操作方法和管道
【发布时间】:2012-09-18 19:27:04
【问题描述】:

我调用了一个 get 操作方法,其中包含传递给该方法的查询字符串参数列表。其中一些参数有一个管道'|'在他们中。问题是我不能有带有管道字符的操作方法参数。如何将管道查询字符串参数映射到非管道 C# 参数?还是有什么我不知道的技巧?

【问题讨论】:

    标签: asp.net-mvc-3 razor query-string actionmethod


    【解决方案1】:

    您可以编写自定义模型绑定器。例如,假设您有以下请求:

    /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
    )
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      相关资源
      最近更新 更多