在尝试将数据填充到我的模型时,我遇到了问题。我有一个“资源”实体,它可以具有无对多的“属性”。我设置了模板,其中包含这些属性的名称。创建资源时,用户选择模板,然后创建属性(空),程序为这些属性生成表单。
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(Model => Model.Resource)
@for (int i = 0; i < Model.Attributes.Count(); i++)
{
<div class="form-group">
@*Html.LabelFor(d => d.Attributes.ToArray()[i].Name, htmlAttributes: new { @class = "control-label col-md-2" })*@
<h4>@Html.Raw(Model.Attributes.ToList()[i].Name)</h4>
<div class="col-md-10">
@Html.TextBoxFor(Model => Model.Attributes.ToList()[i].Value, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(Model => Model.Attributes.ToList()[i].Value, "", new { @class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
此表单使用此View模型:
public class ResourceAttributesViewModel
{
public virtual Resource Resource { get; set; }
public virtual ICollection<_Attribute> Attributes { get; set; }
}
问题是当我点击“提交”按钮时,它给了我具有null资源和属性属性的视图模型
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Fill(ResourceAttributesViewModel AttributeSet)
{
if(ModelState.IsValid)
{
foreach (var attr in AttributeSet.Attributes)
{
db.Entry(attr).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(AttributeSet);
}
如果有帮助,浏览器会发送POST字符串
__RequestVerificationToken=XoVM9h_3njX5x2m35b_vKKHY3m5UDaYm9_2ZMfNkglouqHJCSw2NO56Tv2Sb3kXy8qC8XBLXawoQv0ft0xc-LxYmQGfi4EAqroq2b63Wb9Q1&Resource=System.Data.Entity.DynamicProxies.Resource_7639327FA0332BEBC7FB6836F70C3D62C3D744D76F2C3F8DDFCE679AA8CA31DC&%5B0%5D.Value=100&%5B1%5D.Value=200