views:

90

answers:

3

A while ago, I was trying to pass a dictionary data from my view to my controller. And I was able to do so after googling on the net(remember it was one of scott hanselman's posts). The solution I had was something like

<%for(int index=0; index<Model.Count(); index++){
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties["+index+"].Key"%>"/>
     <input type="hidden" name="<%="properties["+index+"].Value"%>"/>
<%}%>

public ActionResult Process(IDictionary<string,string> properties)
{
      doSomething();
      return View();
}

The code worked for awhile and then I did some refactoring and got rid of this chunk of code. Today, I ran into a situation in which I would like to pass a dictionary again. But no matter how hard I try, the properties parameter received by the action was always null. I tried the above code and

<%for(int index=0; index<Model.Count(); index++){
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties.Keys["+index+"]"%>"/>
     <input type="hidden" name="<%="properties.Values["+index+"]"%>"/>
<%}%>

Neither code worked. I googled again but couldn't find the post that helped me before. Can someone point out what I did wrong? thanks a million.

Update: It turned out that the problem is because the generated html code does not have continous increamenting indexes. For instance, I was getting properties[0], properties[1], properties[3]...(properties[2] was missing). So, firebug would be your best friend when encounting this kind of problems.

A: 

You have your indexer in the wrong place, it has to be an index on the properties object.

<%for(int index=0; index<Model.Count(); index++{
     var property= Model.ElementAt(index);%>
     <input type="hidden" name="<%="properties["+index+"].Key"%>"/>
     <input type="hidden" name="<%="properties["+index+"].Value"%>"/>
<%}%>
Paddy
but the first snippet is exactly what you suggested. It didn't work. By the way, I edited the original post because it was missing a close bracket.
Wei Ma
Sorry, missed the 'neither worked' at the bottom. Have you examined the form collection in the action you post to, to see what is being returned. Also, do you not need a ToString on your indexes for the concatenation?
Paddy
A: 

When i have this kind of problem i allways check the FormCollection Keys, to ensure that it contains the spectated keys, you can do this by putting a breakpoint at the ActionMethod.

public ActionResult Process(IDictionary<string,string> properties, FormCollection f)

And check if "f" has the correct keys.

You can also try

TryUpdateModel(properties, "properties");
Omar
A: 

What way your solution?

Valetudox