Unless your Dictionary
has simple value types for both the Key
and Value
(e.g. public Dictionary<string, string>
), the DefaultModelBinder
requires that the form control name
attributes be in the format
<input .... name="Matrix[0].Key" value="..." />
<input .... name="Matrix[0].Value[0].ID" value="..." />
<input .... name="Matrix[0].Value[0].Name" value="..." />
There are no HtmlHelper
methods that will generate the correct html to allow binding to your Dictionary
.
It is far simpler to create simple view model(s) to with IList<T>
properties for the collections. Based on the view you have shown, those models would be
public class EditVM
{
public int FooID { get; set; }
public List<BarVM> Bars { get; set; }
}
public class BarVM
{
public string Name { get; set; }
public List<BarVersionVM> Versions { get; set; }
}
public class BarVersionVM
{
public int ID { get; set; }
public string Name { get; set; } // not clear where you use this property
public string Version { get; set; }
public bool IsSupported { get; set; }
}
and your view would then be
@model EditVM
....
@Html.HiddenFor(m => m.FooID)
@for(int i = 0; i < Model.Bars.Count; i++)
{
<fieldset>
<legend>@Model.Bars[i].Name</legend>
@Html.HiddenFor(m => m.Bars[i].Name) // in case you need to return the view in the POST method
@for(int j = 0; j < Model.Bars[i].Versions.Count; j++)
{
<div>
@Html.HiddenFor(m => m.Bars[i].Versions[j].ID)
@Html.CheckBoxFor(m => m.Bars[i].Versions[j].IsSupported)
@Html.LabelFor((m => m.Bars[i].Versions[j].IsSupported, Model.Bars[i].Versions[j].Version)
</div>
}
</fieldset>
}
<input type="submit" value="Save" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…