本文介绍了在ASP.NET MVC 2,我可以反序列化查询字符串到使用默认ModelBinder的一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC 2,你可以使用这个网址和该控制器的方法:

  GET HTTP://服务器/控制器/获取ID = 5公众的ActionResult获取(INT ID)
{
    ...
}

而ModelBinder的将转换 ID = 5 中的方法参数查询字符串为 ID =(int)的5 。然而,这是不行的:

  GET HTTP://服务器/控制器/获取IDLIST = 1,2,3,4,5公众的ActionResult获取(INT [] IDLIST)
{
    ...
}

IDLIST 将在参数空。虽然其解析为pretty琐碎,我想知道是否有一种方法可以要么改变方法签名或查询字符串,以使默认ModelBinder的自动反序列化数组/集合?


解决方案

通过默认的模型绑定器,该URL应

<$p$p><$c$c>http://server/controller/get?idlist=1&idlist=2&idlist=3&idlist=4&idlist=5

<$p$p><$c$c>http://server/controller/get?idlist[]=1&idlist[]=2&idlist[]=3&idlist[]=4&idlist[]=5

如果你真的想使用IDLIST = 1,2,3,4,5,你必须有自己的文件夹

In ASP.NET MVC 2, you can use this URL and this controller method:

GET http://server/controller/get?id=5

public ActionResult Get(int id)
{
    ...
}

And the ModelBinder will convert the id=5 querystring to id = (int) 5 in the method parameter. However, this won't work:

GET http://server/controller/get?idlist=1,2,3,4,5

public ActionResult Get(int[] idlist)
{
    ...
}

idlist will be null in the parameter. Although the parsing for this is pretty trivial, I was wondering if there is a way to either change the method signature or the querystring in order to make the default ModelBinder automatically deserialize arrays/collections?

解决方案

With the default modelbinder, the url should be

http://server/controller/get?idlist=1&idlist=2&idlist=3&idlist=4&idlist=5

or

http://server/controller/get?idlist[]=1&idlist[]=2&idlist[]=3&idlist[]=4&idlist[]=5

If you really want to use idlist=1,2,3,4,5, you should have your own binder

这篇关于在ASP.NET MVC 2,我可以反序列化查询字符串到使用默认ModelBinder的一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:23