简而言之:如何成功编辑数据库条目,而无需在编辑视图中包含模型的每个字段?
更新
所以我在数据库中有一个项目(一篇文章)。我想编辑一篇文章。我编辑的文章有很多属性(Id、CreatedBy、DateCreated、Title、Body)。其中一些属性永远不需要更改(如 Id、CreatedBy、DateCreated)。所以在我的编辑视图中,我只想要可以更改的字段(如标题、正文)的输入字段。当我实现这样的编辑视图时,模型绑定失败。我没有提供输入的任何字段都设置为某个“默认”值(例如 DateCreated 设置为 01/01/0001 12:00:00am)。如果我这样做为每个字段提供输入,一切正常,文章按预期编辑。我不知道说“模型绑定失败”是否正确,就像“如果在编辑视图中没有为它们提供输入字段,系统会用不正确的数据填充字段”。
如何以只需要为可以/需要编辑的字段提供输入字段的方式创建编辑视图,以便在调用 Controller 中的 Edit 方法时,正确填充 DateCreated 等字段,而不是设置到一些默认的、不正确的值?这是我目前的编辑方法:
[HttpPost]
public ActionResult Edit(Article article)
{
// Get a list of categories for dropdownlist
ViewBag.Categories = GetDropDownList();
if (article.CreatedBy == (string)CurrentSession.SamAccountName || (bool)CurrentSession.IsAdmin)
{
if (ModelState.IsValid)
{
article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
article.LastUpdated = DateTime.Now;
article.Body = Sanitizer.GetSafeHtmlFragment(article.Body);
_db.Entry(article).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(article);
}
// User not allowed to edit
return RedirectToAction("Index", "Home");
}
如果有帮助,请编辑视图:
. . .
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Article</legend>
<p>
<input type="submit" value="Save" /> | @Html.ActionLink("Back to List", "Index")
</p>
@Html.Action("Details", "Article", new { id = Model.Id })
@Html.HiddenFor(model => model.CreatedBy)
@Html.HiddenFor(model => model.DateCreated)
<div class="editor-field">
<span>
@Html.LabelFor(model => model.Type)
@Html.DropDownListFor(model => model.Type, (SelectList)ViewBag.Categories)
@Html.ValidationMessageFor(model => model.Type)
</span>
<span>
@Html.LabelFor(model => model.Active)
@Html.CheckBoxFor(model => model.Active)
@Html.ValidationMessageFor(model => model.Active)
</span>
<span>
@Html.LabelFor(model => model.Stickied)
@Html.CheckBoxFor(model => model.Stickied)
@Html.ValidationMessageFor(model => model.Stickied)
</span>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@* We set the id of the TextArea to 'CKeditor' for the CKeditor script to change the TextArea into a WYSIWYG editor. *@
@Html.TextAreaFor(model => model.Body, new { id = "CKeditor", @class = "text-editor" })
@Html.ValidationMessageFor(model => model.Body)
</div>
</fieldset>
. . .
如果我要省略这两个输入:
@Html.HiddenFor(model => model.CreatedBy)
@Html.HiddenFor(model => model.DateCreated)
当调用 Edit 方法时,它们被设置为默认值。CreatedBy 设置为Null, Created 设置为01/01/0001 12:00:00am
为什么它们没有设置为当前在数据库中设置的值?