如果我在模型上有一组项目,我将如何将一个项目绑定到基于外部变量的视图中的字段。
假设我有这个模型:
public class Element
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid ID { get; set; }
public virtual IList<ElementData> Data { get; set; }
[NotMapped]
public ElementData CurrentData
{
get
{
if (Data == null)
return null;
ElementData data = Data.FirstOrDefault(x => x.LanguageID == MyContext.Current.Language.ID);
if (data == null)
data = Data.FirstOrDefault(x => x.LanguageID == MyContext.Current.DefaultLanguage.ID);
return data;
}
}
}
public class ElementData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid ID { get; set; }
[Required]
[ForeignKey("Element")]
public Guid ElementID { get; set; }
[Required]
[ForeignKey("Language")]
public Guid LanguageID { get; set; }
public virtual Element Element { get; set; }
public virtual Language Language { get; set; }
}
看法:
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.CurrentData.ID)
<header class="editor-header">
<div class="editor-title">
@Html.EditorFor(model => model.CurrentData.Name)
@Html.ValidationMessageFor(model => model.CurrentData.Name)
</div>
</header>
<hr />
<div class="editor-field">
@Html.LabelFor(model => model.CurrentData.Content)
@Html.EditorFor(model => model.CurrentData.Content)
@Html.ValidationMessageFor(model => model.CurrentData.Content)
</div>
控制器:
[HttpPost]
public string Edit(Element element)
{
if (ModelState.IsValid)
{
db.Entry(element).State = EntityState.Modified;
db.Entry(element.CurrentData).State = EntityState.Modified; // Exception here as CurrentData is null
db.SaveChanges();
return "success";
}
}
我正在使用这个 ajax 发回这些数据:
$(function () {
$(document).on("submit", "form", function (evt) {
evt.preventDefault();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
该模型在控制器中有效,但显然它不会重新填充我的 ElementData 列表,因为它无法通过 CurrentData 执行此操作。我怀疑我只是不知道如何正确绑定元素数据列表中的一项,但我找不到允许我从列表中挑选出一项的指南。