[英]View and Edit nested Dictionaries within the same model in a Razor view and save them back to the model
我有以下模型:
public class FormDimensions
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "formID")]
public String FormID { get; set; }
[JsonProperty(PropertyName = "width")]
public float Width { get; set; }
[JsonProperty(PropertyName = "height")]
public float Height { get; set; }
[JsonProperty(PropertyName = "padding")]
public float Padding { get; set; }
[JsonProperty(PropertyName = "inspectedFields")]
public Dictionary<String, Dictionary<String,FieldDimension>> InspectedFields { get; set; }
}
字段“ InspectedFields”是有问题的字段。
public class FieldDimension
{
[JsonProperty(PropertyName = "name")]
public String Name { get; set; }
[JsonProperty(PropertyName = "page")]
public int Page { get; set; }
[JsonProperty(PropertyName = "dimension")]
public String Dimension { get; set; }
}
我在模型的“编辑剃刀”视图中一直使用以下代码:
foreach (var entry in Model.InspectedFields)
{
<h3>@entry.Key</h3>
<div class="card-block">
@foreach (var page in entry.Value.Values)
{
<div class="form-group">
@Html.Label("Value Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => page.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessage(page.Name, new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label("Page Dimensions", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => page.Dimension, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessage(page.Dimension, new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label("Page Number", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => page.Page, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessage(page.Page.ToString(), new { @class = "text-danger" })
</div>
</div>
}
</div>
<hr />
}
因此,当我保存模型时,它实际上使整个InspectedFeilds词典无效,并导致我的剃刀视图崩溃。 但是,它将所有其他值保存在模型中。 我不确定这是因为我的实现还是我在剃刀视图中缺少有关处理字典的某些知识。
为了发布字典,您必须同时发布Key
和Value
。 您还需要使用for循环并为字典建立索引。 例如:
@for (var i = 0; i < Model.InspectedFields.Count; i++)
{
@Html.HiddenFor(m => m.InspectedFields[i].Key)
for (var j = 0; j < Model.InspectedFields[i].Value.Count; j++)
{
@Html.HiddenFor(m => m.InspectedFields[i].Value[j].Key)
@Html.EditorFor(m => m.InspectedFields[i].Value[j].Value.Page)
}
}
从示例代码中删除了HTML,以更好地说明该格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.