I have looked around on the Internet, but none of the solutions seem to work for me.
I have the following view model:
public class ConfigsViewModel
{
// iOS Dictionary
public Dictionary<string, object> IosDictionary { get; set; }
// Android Dictionary
public Dictionary<string, object> AndroidDictionary { get; set; }
}
The values in these dictionaries are either bool or strings. I want to display a table like editing view, and I want to bind these dictionaries. My view looks like this:
@model MobileRebrandingTool.Models.ViewModels.ConfigsViewModel
<div>
@using (Html.BeginForm("SaveAppConfig", "Project", "POST"))
{
<table class="config-table">
<tr>
<th></th>
<th>iOS</th>
<th>Android</th>
</tr>
@foreach (var kvp in Model.IosDictionary)
{
<tr>
<td>
@kvp.Key
</td>
<td>
@Html.EditorFor(model => model.IosDictionary[kvp.Key])
</td>
<td>
@if (Model.AndroidDictionary.ContainsKey(kvp.Key))
{
@Html.EditorFor(model => model.AndroidDictionary[kvp.Key])
}
</td>
</tr>
}
</table>
<input type="submit" value="Save"/>
}
</div>
The problem is that in SaveAppConfig action, when I check the model, instead of a string as value for the keys in the dictionaries, the value is an array of one string (the value in the text input). In the dictionaries I have as values bools and strings, so I cannot use TextBoxFor. Is there a better way to bind the dictionaries? Should I write a custom binder? And if so, how should it look like?
Thank you,
Cosmin
Since you are in the foreach you need to pull the value a little differently
should be something like
I am not 100% sure you can do kvp.Value. Looked up iterating through a dictionary and found this What is the best way to iterate over a Dictionary in C#?