Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - HiddenFor Dictionary Values

I have a dictionary property called Week:

public IDictionary<DayOfWeek, Day> Week { get; private set; }

And I'm trying to pass its values off to HiddenFor (Days)

@Html.HiddenFor(x => x.Week.Values)

It has to be a property of the Model so I can't do x.Week.Values.ToList();

How would I go about passing the Dictionary Values to the Html.HiddenFor?

like image 684
Nate-Wilkins Avatar asked Jul 14 '26 17:07

Nate-Wilkins


2 Answers

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>
like image 188
Jason Kulatunga Avatar answered Jul 16 '26 06:07

Jason Kulatunga


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">
like image 25
kristianp Avatar answered Jul 16 '26 06:07

kristianp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!