我正在尝试更新已更新到数据库的文本和图像。我有一个管理部分,其中有一个新闻菜单,用户可以使用图像编辑和更新新闻。问题是我可以编辑和更新新闻文本,但图像不会更新。下面是控制器和视图:
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(int id, FormCollection collection, IEnumerable<HttpPostedFileBase> files)
{
INewsRepository newsResp = new NewsRepository();
News news = newsResp.GetNews(id);
if (TryUpdateModel(news)){
newsResp.Save();
return RedirectToAction("Index");
}else{
return View();
}
}
<% using (Html.BeginForm("Edit", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<%: Html.ValidationSummary(true) %>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<td style="width:100px;">
<div class="editor-label">
Title</div>
</td>
<td>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title, new { style = "width:300px;" })%>
<%: Html.ValidationMessageFor(model => model.Title)%>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="editor-label">
Article content</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="editor-field">
<%: Html.TextAreaFor(model => model.Article, new { @class = "tinymce" })%>
<%: Html.ValidationMessageFor(model => model.Article)%>
</div>
</td>
</tr>
<tr>
<td>
Image 1
</td>
<td>
<img height="56px" width="75px" alt="image1" src="/content/images/content/<%: Model.ImageLarge %>" />
<br />
<input type="file" name="files" id="file1" />
</td>
</tr>
<tr>
<td>
Image 2
</td>
<td>
<img height="56px" width="75px" alt="image1" src="/content/images/content/<%: Model.ImageLarge2 %>" />
<br />
<input type="file" name="files" id="file2" />
</td>
</tr>
<tr>
<td>
Image 3
</td>
<td>
<img height="56px" width="75px" alt="image1" src="/content/images/content/<%: Model.ImageLarge3 %>" />
<br />
<input type="file" name="files" id="file3" />
</td>
</tr>
</table>
<p>
<input type="submit" value="Save" />
</p>
<% } %>
答案 0 :(得分:0)
TryUpdateModel
不会更新文件。您可以手动将流复制到News
模型的相应属性中:
foreach (var file in files)
{
byte[] buffer = new byte[file.InputStream.Length];
file.InputStream.Read(buffer, 0, buffer.Length);
news.Files.Add(buffer);
}