简体   繁体   中英

asp.net web api - model binding list parameter

In my controller I have:

[AcceptVerbs("GET", "POST")]
    public List<BuzzMonitor.Web.Message> Search(string text, DateTime dateFrom, DateTime dateTo, List<int> themeIds, List<int> sourceIds) 
    {...}

and I want to do model binding. It's easy for primitive types, but what to do when I have a list of primitive types?

I did it like this in Global.asax:

 GlobalConfiguration.Configuration.Routes.MapHttpRoute("SearchWithParameters", "api/{controller}/{action}/{text}/{dateFrom}/{dateTo}/?/?"

But I dont know what to set for lists...

I found on some site that I can add [ModelBinder] before list, but when I do that I just get red underline on that word.

Does anyone have an idea how to do it?

From your description it looks like you have found this article or one like it

http://lostechies.com/keithdahlby/2012/10/04/asp-net-web-api-list-parameter-binding/

recommending you use the ModelBinder attribute. I still recommend this way if you can get it to work. The red underline you describe sounds like you may not have the appropriate references. Please make sure you have the appropriate references in your class to access that attribute, in this case it looks like System.Web.Http.ModelBinding

http://msdn.microsoft.com/en-us/library/system.web.http.modelbinding.modelbinderattribute(v=vs.118).aspx

If that fails you will likely not be able to use Model Binding. From the first article

Web API only uses model binding for “simple types”

you can also look at using a JSON Formatter or similar, this is not difficult and would easily support List structures, with well formatted JSON.

here is a great introductory article to using this

http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM