在我的 ASP.NET MVC 4 应用程序中,我可以过滤多个标签。在 HTML 中,它看起来像这样:
<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
我的控制器很好地传递了具有以下类类型的对象:
// 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
结果是序列化集合的类型名,而不是实际值。
如何才能做到这一点?
MVC 的标准基础设施可以处理描述为输入的多键。是否没有标准基础设施可以以相反的方式处理它?我错过了什么吗?
您可以通过以下方式进行操作:
string url = Url.Action("DoFilter", TypeHelper2.ObjectToDictionary(filter) );
The TypeHelper2.ObjectToDictionary
是.NET内部方法的修改版本,可以在这里找到两个文件要点 https://gist.github.com/doekman/b5fbe3944bfe0283670e.
改变的行为:当一个项目实现时IEnumerable
,对于每个项目,一个条目是
在返回的字典中创建作为键"Name[index]"
(索引从 0 开始)。这是可能的,因为 MVC 控制器的绑定器可以处理两者tag=1&tag=3
and tag[0]=1&tag[1]=3
查询字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)