我希望这个问题有一个简单的答案,我只是没有看到。
我正在开发一个 asp.net MVC 4 应用程序。基本上,我希望允许用户编辑他们将制作的上一个条目(新闻文章)的内容(听起来很容易)这个条目由一个日期、两个文本块、(标题和正文)一个 img 组成。这些条目对应于模型的属性,其中还包括 ID、img 名称和状态。我已经成功地在需要时输入、保存和检索所有数据。但是,当我运行程序并尝试编辑以前的条目时,它只会保存标题和正文,并删除那里的值,包括日期、img、img 名称和状态。
这与视图中使用的文本框有关吗?为什么保留这些值而其他值不保留。
只是要指出,当我运行并选择一个条目时,所有数据都正确显示,但是当我单击保存时,值被删除(日期、img 名称、状态)
有什么想法吗.....
控制器....
public ActionResult Edit(int id)
{
String encodedBody;
NewsArticle newsArticle = _newsArticle.Get(id);
encodedBody = HttpUtility.HtmlDecode(newsArticle.Body.ToString());
newsArticle.Body = encodedBody;
return View(newsArticle);
}
// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle)
{
try
{
if (ModelState.IsValid)
{
db.Entry(newsArticle).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}
看法.......
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", id = "newsEditForm"}))
{
@Html.ValidationSummary()
@Html.HiddenFor(model => model.ID)
<div class="control-group">
<label class="control-label">Posted on :</label>
<div class="controls">
<span class="text">@Model.DateCreated.Value.ToShortDateString()</span>
@*@Html.LabelFor(n => n.DateCreated)*@
</div>
</div>
<div class="control-group">
<label class="control-label">@Html.LabelFor(n => n.Title)</label>
<div class="controls">
@Html.TextBoxFor(n => n.Title, new { @class = "span4 m-wrap", rows = 1})
</div>
</div>
<div class="control-group">
<label class="control-label">@Html.LabelFor(n => n.Body)</label>
<div class="controls">
@Html.TextAreaFor(n => n.Body, new { @class = "span12 ckeditor m-wrap", rows = 4 })
</div>
</div>
<div class="control-group">
<label class="control-label">Selected Image </label>
<label class="controls">@Html.DisplayTextFor(model => model.ImageName)</label>
@* <div class="span4 blog-img blog-tag-data">
<div class="editor-field">
<input type="file" name="Article" id="ArticleImage"/>
</div>
</div>*@
</div>
<div class="form-actions">
<button type="submit" class="btn green" id="submitnews"><i class="icon-ok"></i>Submit</button>
@Html.ActionLink("Cancel", "ArticleList", "Admin", null, new { @class = "btn blue"})
@*<button type="button" class="btn blue" onclick="location.href='ArticleList','Admin'">Cancel</button>*@
</div>
}