我一直在使用Google的解决我的问题了两天,没有任何运气。 MVC3 .NET中的任何明星都可以提供帮助吗?保存在数据库中的图像无法更新
我想建立一个.NET MVC3应用程序更新保存在数据库中的图像。
这里是操作方法
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
//var img = (from imga in db.myImages
// where imga.imageID == id
// select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
img.imageType = imageFile.ContentType;
img.Data = new byte[imageFile.ContentLength];
imageFile.InputStream.Read(img.Data, 0, imageFile.ContentLength);
}
// save the product
UpdateModel(img);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
这里是视图
@model JackLing.Models.myImage
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Edit", "Image",FormMethod.Post, new { enctype = "multipart/form-data" })){
@Html.ValidationSummary(true)
<fieldset>
<legend>myImage</legend>
@Html.EditorForModel();
<div class="editor-label">Image</div>
<div class="editor-field">
@if (Model.Data != null)
{
<img src="@Url.Action("show", new { id = Model.imageID })" height="150" width="150" />
}
else {
@:None
}
</div>
<p>
<span>Choose a new file</span> <input type="file" name="imgFile"/>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
当运行它抛出一个错误说应用程序“对象引用不设置为一个对象的一个实例。”
就如何解决这些问题的任何建议将appriciated!顺便说一下,创建和细节方法都是可行的。我认为它与数据绑定有关,但我不确定...我不知道如何解决它。
最后固定的基础上,从Eulerfx 建议这里的问题是工作的行动。
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
myImage imgToSave = (from imga in db.myImages
where imga.imageID == img.imageID
select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
imgToSave.imageType = imageFile.ContentType;
var binaryReader = new BinaryReader(imageFile.InputStream);
imgToSave.Data = binaryReader.ReadBytes(imageFile.ContentLength);
binaryReader.Close();
}
TryUpdateModel(imgToSave);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
你能证明你的GET操作? – 2012-07-19 14:57:39
哪一行代码会抛出“对象引用”错误? – MikeTWebb 2012-07-19 15:00:23
非常感谢您的回复!这里是获取操作public ActionResult编辑(int id) { myImage mi =(from img in db.myImages where img.imageID == id select img).First(); return View(mi); } – 2012-07-19 22:18:44