Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
7.4k views
in Technique[技术] by (71.8m points)

ASP.NET MVC - get list of objects from query string

I'm passed a list of parameters. Such as "Name", "Id", "Type". There will be an many of these in url, like so:

"Name=blah1,Id=231,Type=blah1;Name=blah2,Id=2221,Type=blah1;Name=blah3,Id=45411,Type=blah3;"

I wonder if there is a way to map these query parameters to a List of objects. So, I can create an object:

MyTestObject {Name;Id;Type} and can say in my controller

Index(IList<MyTestObject> params)

params will be filled in with data from query string.

Something that is similar to http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I actually followed advice in the article by Mr. Haack I created a class with all of the parameters as public properties. Then I had a view take a list of objects of that type. If the query parameter names follow a certain pattern (prepended by index) then I get a list of my object automatically populated and I don't have to do any manual parsing at all. This is the simplest solution for me.

Example:

query param object:

public class QueryParams
{
   public string Id,
   public string Name,
   public string Type
}

in controller method:

public ActionResult Index(IList<QueryParams> queryData)

then I make sure that query string is formated in the following way(prepended by index):

http://localhost/myapp/?[0].id=123&[0].Name=blah&[0].Type=Person&[1].Id=345&[1].Name=example&[1].Type=Stuff

In my controller, queryData list parameter will contain two objects populated with correct data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...