.net – MVC3与EF 4.1和EntityState.Modified更新
发布时间:2020-12-16 03:25:32 所属栏目:asp.Net 来源:网络整理
导读:在使用.NET MVC3更新对象时,我在理解EntityState.Modified方面遇到了问题. 我有一个模型,可以在上传图像时存储ImageFilePath和ImageContentType.这是创建动作的样子. [HttpPost] public ActionResult Create(SneakPeekCollection collection,HttpPostedFileB
在使用.NET MVC3更新对象时,我在理解EntityState.Modified方面遇到了问题.
我有一个模型,可以在上传图像时存储ImageFilePath和ImageContentType.这是创建动作的样子. [HttpPost] public ActionResult Create(SneakPeekCollection collection,HttpPostedFileBase image) { try { if (image != null) { var filepath = Path.Combine(HttpContext.Server.MapPath("../../Uploads"),Path.GetFileName(image.FileName)); image.SaveAs(filepath); collection.ImageContentType = image.ContentType; collection.ImageFilePath = "~/Uploads/" + image.FileName; } _db.SneakPeekCollections.Add(collection); _db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } 尝试编辑并随后更新此对象时出现问题.这是我的编辑操作. [HttpPost] public ActionResult Edit(int id,SneakPeekCollection collection,HttpPostedFileBase image) { try { if (image != null) { var filepath = Path.Combine(HttpContext.Server.MapPath("../../../Uploads"),Path.GetFileName(image.FileName)); image.SaveAs(filepath); collection.ImageContentType = image.ContentType; collection.ImageFilePath = "~/Uploads/" + image.FileName; } _db.Entry(collection).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } 我认为问题来自于我正在设置EntityState.Modified,它将所有属性标记为已修改.如果我没有上传新图像,那么来自前端的ImageFilePath和ImageContentType实际上是null,这是存储的内容. 我的问题是如何解决这个问题?使用EntityState.Modified的正确方法是什么? 解决方法
您可以从db中检索模型,并使用UpdateModel获取新值(如果存在),而不是通过在参数中接受SneakPeakCollection来使用隐式模型绑定.像这样的东西:
var collection = _db.SneakPeaks.Find(id); // Get the entity to update from the db UpdateModel(collection); // Explicitly invoke model binding if (image != null) { var filepath = Path.Combine(HttpContext.Server.MapPath("../../../Uploads"),Path.GetFileName(image.FileName)); image.SaveAs(filepath); collection.ImageContentType = image.ContentType; collection.ImageFilePath = "~/Uploads/" + image.FileName; } _db.SaveChanges(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET使用VB设置文件的路径
- 如何保护我的ASP.NET AJAX应用程序?
- 是否可以在IIS中禁用ASP.NET网站睡眠?
- asp.net – 如何验证文件上传的文件类型?
- asp.net – 创建新的实体数据模型的麻烦
- asp.net-mvc-3 – ASP.NET MVC中全局错误/异常处理的最佳实
- asp.net-mvc-2 – ASP.NET:ActionLink返回相对url
- asp.net-mvc – 为什么在为JavaScript分配Model值时ASP.Net
- asp.net – 想要在ModalPopExtender之上显示Update Progres
- ASP.NET会话状态在异常后丢失
推荐文章
站长推荐
- vbscript – 从ASP脚本使用wscript.shell时无法引
- .resx本地化不能与ASP.Net一起使用 – C#
- asp.net-mvc – 如何在mvc网格格式中格式化日期
- ASP.NET:编译器失败,错误代码为-532462766
- asp.net-mvc – 为什么必须将LESS文件设置为Buil
- asp.net-mvc – 为什么ASP.Net MVC(或CodeIgnite
- asp.net-mvc – 如何从编辑器模板添加JavaScript
- asp.net-mvc – 疑难解答反伪造令牌问题
- asp.net – 可以在正则表达式中执行加法吗?
- asp.net – Orchard CMS是否支持移动呈现?
热点阅读