Hidden input for Dictionary<string, string> in ASP.NET MVC 3

烈酒焚心 提交于 2019-12-05 09:54:29

You need two hidden fields one for the Key and one for the Value if you want to modelbind to a 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, you will be also need a running index to make the model binder happy.

Or if you don't want to have a running you can solve with an 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 a lots of info about modelbinding with collections in this two article:

Change your post action to this

[HttpPost]
public ActionResult MyPostAction(ViewModel model, ViewPart viewPart)
{
    model.ViewPart.Flags = viewPart.Flags;
}

and in the view use

@foreach(var item in Model.ViewPart.Flags) { 
  @Html.HiddenFor(modelItem => item)
}

If this doesn't work, check the source of the rendered HTML and see if the the Hidden information is rendered. I'm not sure if @Html.HiddenFor will work with a Dictionary you may need to write it out like you had done previously if it doesn't.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!