Hidden input for Dictionary in ASP.NET MVC 3 -


i need model properties in post action, need hidden element them, have problem type of dictionary <string, string>. model:

public class viewmodel{ ... public viewpart viewpart { get; set; } } public class viewpart { ... public dictionary<string, string> flags { get; set; } } 

and controller:

dictionary<string, string> flags = new dictionary<string, string>(); flags.add("kind", "edit"); flags.add("command", "save"); viewmodel model = new viewmodel(){ flags = flags }; return view(model); 

in view:

@foreach(var item in model.viewpart.flags) { <input type="hidden" id="viewpart_flags_@(item.key)" value="@item.value" name="viewpart.flags[@(item.key)]" /> } 

also try 1 :

@foreach(var item in model.viewpart.flags) { @html.hiddenfor(modelitem => item) } 

update post action:

[httppost] public actionresult mypostaction(viewmodel model){ //model.viewpart.flags null } 

but in post action flags null, why? fault? there better way pass variables view action?

you need 2 hidden fields 1 key , 1 value if want modelbind dictionary:

var index = 0; foreach (var item in model.viewpart.flags) { <input type="hidden" value="@item.key" name="viewpart.flags[@(index)].key"/> <input type="hidden" value="@item.value" name="viewpart.flags[@(index)].value"/> index++; } <input type="submit" value="save"/> 

note, need running index make model binder happy.

or if don't want have running can solve addtional hidden index field:

foreach (var item in model.viewpart.flags) { <input type="hidden" value="@item.key" name="viewpart.flags.index"/> <input type="hidden" value="@item.key" name="viewpart.flags[@(item.key)].key" /> <input type="hidden" value="@item.value" name="viewpart.flags[@(item.key)].value" /> } <input type="submit" value="save"/> } 

you can find lots of info modelbinding collections in 2 article:


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -