In ASP.NET MVC 2, can I deserialize a querystring into an array using the default ModelBinder?

為{幸葍}努か 提交于 2019-12-10 17:12:00

问题


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?


回答1:


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




回答2:


This is a little late to the party but I wanted to do exactly the same thing.

You can pass the single string as {1,2} and it the binder will bind it to an array e.g

<input name="idlist" type="text" value="{163,162}">



回答3:


Here's what I think:

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

Should be used as

GET http://server/controller/get/5

And the idlist can be simply split by comma(,)



来源:https://stackoverflow.com/questions/4394165/in-asp-net-mvc-2-can-i-deserialize-a-querystring-into-an-array-using-the-defaul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!