如何使用具有相同名称的多个值的RouteValues [英] How to work with RouteValues with multiple values of the same name

查看:94
本文介绍了如何使用具有相同名称的多个值的RouteValues的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC 4应用程序中,我可以过滤多个标签.在HTML中,它看起来像这样:

In my ASP.NET MVC 4 application I can filter on multiple tags. In HTML, it looks like this:

<form>
  <label>
    <input type="checkbox" name="tag" value="1">One
  </label>
  <label>
    <input type="checkbox" name="tag" value="2">Two
  </label>
  <label>
    <input type="checkbox" name="tag" value="3">Three
  </label>
  <input type="submit" name="action" value="Filter">
</form>

在选中第一个和第三个复选框时,查询字符串被序列化为?tag = 1& tag = 3 ,并且我的控制器很好地传递了具有以下类类型的对象:

When checking the first and third checkbox, the querystring is serialized as ?tag=1&tag=3 and my controller nicely passes an object with the type of the following class:

// Filter class
public class Filter { 
    public ICollection<int> tag { get; set; }
}

// Controller method
public ActionResult Index(AdFilter filter)
{
    string url = Url.Action("DoFilter", filter);
    // url gets this value:
    // "/controller/Index?tag=System.Collections.Generic.List%601%5BSystem.Int32%5D"
    // I would expect this:
    // "/controller/Index?tag=1&tag=3"
    ...
 }

但是,对 Url.Action 的调用会导致对集合的类型名进行序列化,而不是实际值.

However, a call to Url.Action results in the typename of the collection being serialized, instead of the actual values.

这怎么办?

MVC的标准基础结构可以处理描述为输入的多键.是否没有标准的基础架构可以反其道而行之?我想念什么吗?

The standard infrastructure of MVC can handle the multi-keys described as input. Is there not standard infrastructure that can handle it the other way around? Am I missing something?

推荐答案

您可以通过以下方式进行操作:

You can do it in the following way:

string url = Url.Action("DoFilter", TypeHelper2.ObjectToDictionary(filter) );

TypeHelper2.ObjectToDictionary 是.NET内部方法的修改版本,可以在此

The TypeHelper2.ObjectToDictionary is a modified version of an internal method of .NET, and can be found in this two file gist.

已更改的行为:当一个项目实现 IEnumerable 时,对于每个项目,都会有一个条目在返回的字典中使用键"Name [index]" 创建索引(索引从0开始).这是可能的,因为MVC控制器的绑定程序可以处理 tag = 1& tag = 3 tag [0] = 1& tag [1] = 3 查询字符串

Changed behavior: when an item implements IEnumerable, for each item an entry is created in the returned dictionary with as key "Name[index]" (the index is 0 based). This is possible because the binder of the MVC controller can handle both tag=1&tag=3 and tag[0]=1&tag[1]=3 query strings.

这篇关于如何使用具有相同名称的多个值的RouteValues的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆