0

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??

tereško
  • 58,060
  • 25
  • 98
  • 150
Bartosz
  • 4,542
  • 11
  • 43
  • 69

2 Answers2

1

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.

Peter
  • 7,792
  • 9
  • 63
  • 94
0

For some strange reason when I removed "survey" and left iteration by itself (i.e. [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???

Bartosz
  • 4,542
  • 11
  • 43
  • 69
  • This has likely changed now that this bug is fixed: http://connect.microsoft.com/VisualStudio/feedback/details/636647/make-jsonvalueproviderfactory-work-with-dictionary-types-in-asp-net-mvc - You probably just use a simple JSON object. Note: Have not had a chance to test this new functionality in MVC4, we currently use the MVC3 workaround: http://stackoverflow.com/questions/4710729/post-json-dictionary/5397743#5397743 – Chris Moschini Oct 23 '12 at 17:34
  • Thanks for answer but it was straight binding. No JSON involved. – Bartosz Oct 23 '12 at 21:25
  • Well, that's what I mean - according to that bug fix you should now be able to skip the workaround and just submit a JS object and get a Dictionary on the other end, instead of the .Key/.Value hack or a custom serialization hack. – Chris Moschini Oct 24 '12 at 07:48