简体   繁体   中英

Mvc4 default model binder - Dictionary

I have a form which posts these values:

survey[0].Key 75

survey[0].Value 4

survey[1].Key 76

survey[1].Value 4

I'm trying to use a default model binder to map it onto Dictionary type:

[HttpPost]
public ActionResult CompleteSurvey(Dictionary<int, int> answers)
{
...
}

but I get InvalidCastException: Specified cast is not valid.

Why??

Im just guessing here but i think It's because your argument is called 'answers' not 'survey'. You should look at what is being posted to your method by looking in the post headers easy to do in firebug or chrome. It makes more sense when you inspect the stuff being transmitted 'over the wire'

The cast not valid thing is probably because in your scenario answers is null when the model binder wants to do its job. If you used formscollection instead of dictionary you'd find everything you post is there.

For some strange reason when I removed "survey" and left iteration by itself (ie [0].Key) binding works fine.

I was basing my knowledge on this article: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx which appears to be wrong then??? or does it refer to the previous versions of MVC???

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