asp.net mvc - How to store Dictionary<string, string> in hidden field and retrieve the same in controller through FormCollection Id -
the scenario :-
controller part :
public actionresult goht() { dictionary<string, string> col = new dictionary<string, string>(); col.add("a", "c"); col.add("b", "c"); viewbag.cols = col; return view(); }
view part :
<input type="hidden" id="hd" name ="hd" value="@viewbag.cols" />
in case hidden value not showing dictionary element id defined instead show as
<input type="hidden" id="hd" name="hd" value="system.collections.generic.dictionary`2[system.string,system.string]">
here question , how assign dictionary element viewbag , store in hidden field.
and how same dictionary made available @ form submission.
controller :
[acceptverbs(httpverbs.post)] public actionresult goht(formcollection formcollection) { var mode = (dictionary<string, string>)formcollection["hd"].tostring(); }
you need multiple hidden fields, each key in dictionary. scott hanselman wrote nice blog post
explaining how hidden fields should named. way able retrieve values typed dictionary object in controller.
<input type="text" name="col[0].key" value="a" /> <input type="text" name="col[0].value" value="c" /> <input type="text" name="col[1].key" value="b" /> <input type="text" name="col[1].value" value="c" /> ...
now controller action directly take dictionary parameter:
[httppost] public actionresult goht(dictionary<string, string> col) { // col here ... }
so that's left loop through values of dictionary , generate hidden fields:
@foreach (var item in (dictionary<string, string>)viewbag.cols) { @html.hidden("cols.key", item.key) @html.hidden("cols.value", item.value) }
Comments
Post a Comment