我正在使用ASP.NET MVC 4,我有以下模型:
public class MultiLanguageText
{
[Key] public int Id { get; set; }
[Required] public string Name { get; set; }
public virtual ICollection<LocalizedText> LocalizedTexts { get; set; }
}
public class LocalizedText
{
[Key] public int Id { get; set; }
[ForeignKey("Language")] public int LanguageId { get; set; }
public virtual Language Language { get; set; }
[ForeignKey("MultiLanguageText")] public int MultiLanguageTextId { get; set; }
public virtual MultiLanguageText MultiLanguageText { get; set; }
public string Text { get; set; }
}
我正在尝试为MultiLanguageText
创建一个编辑视图,该视图还将包含LocalizedTexts
属性中每个项目的编辑器。表格如下:
@using (Html.BeginForm("Edit", "MultiLanguageText", FormMethod.Post)) {
@Html.ValidationSummary(true)
<fieldset>
<legend>MultiLanguageText</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
@Html.EditorFor(model => model.LocalizedTexts)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
我创建的编辑器模板(在文件~/Views/Shared/EditorTemplates/LocalizedText.cshtml
中)如下:
<fieldset>
<legend>LocalizedText</legend>
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.LanguageId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LanguageId)
@Html.ValidationMessageFor(model => model.LanguageId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MultiLanguageTextId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MultiLanguageTextId)
@Html.ValidationMessageFor(model => model.MultiLanguageTextId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
</fieldset>
我正在使用一些预先存在的值进行测试,并且当显示页面时,所有数据都会在父级和子编辑器中正确显示。但是,当我提交表单时,将忽略在任何子编辑器中完成的所有更改。
我的HttpPost
方法是:
[HttpPost]
public ActionResult Edit(MultiLanguageText multilanguagetext)
{
if (ModelState.IsValid)
{
db.Entry(multilanguagetext).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(multilanguagetext);
}
我的问题是:我如何制作以便从父模型及其子模型编辑器发布所有值?(我看到其他类似问题存在,但我他们已经尝试过他们的解决方案而且似乎没有解决我的问题。)
答案 0 :(得分:0)
我正在测试你的问题。我认为已经完成并发布了所有价值观。但我认为您需要提供更多信息来解决您的问题
答案 1 :(得分:0)
经过一番尝试,这是我发现的解决方案:
[HttpPost]
public ActionResult Edit(MultiLanguageText multilanguagetext)
{
if (ModelState.IsValid)
{
db.Entry(multilanguagetext).State = EntityState.Modified;
foreach (var local in multilanguagetext.LocalizedTexts) db.Entry(local).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(multilanguagetext);
}