MVC3 - HiddenFor Dictionary Values

感情迁移 提交于 2019-12-06 01:43:29
Jason Kulatunga

Well since your using HiddenFor, I'm going to assume that you need to rebind the values of the dictionary on form post. To bind a Dictionary to the view, your going to need to do something like this:

@foreach (var key in Model.Week.Keys)
{
    Html.DisplayFor(model=>model.Week[key]);
}

Each value in the dictionary will be given its own Hidden Input field, with the name attribute: name="Week.{key here}

If, on the other hand, all you need to do is send the data in your model to the client so that you can do something with it in JavaScript, you might want to look at writing it to the page as JSON.

<script type="text/javascript">
@Html.Raw(Json.Encode(Model.Week))
</script>

I would use:

@foreach (var key in Model.Week.Keys)
{
    @Html.HiddenFor(model=>model.Week[key]);
}

The '@' before the Html seems necessary for razor to output the hidden fields.

It outputs something like this for each key:

<input data-val="true" data-val-number="The field Int32 must be a number." 
   data-val-required="The Int32 field is required." id="Week_5_" name="Week[5]" 
   type="hidden" value="3">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!