MVC .NET 如何通过文件上传最好地更新模型
使用 EF4 Codefirst RC 和 MVC .NET
我有一个强类型视图,用于在模型上执行插入/更新操作。 其中一个字段是上传的文件/图像。我使用下面的代码来执行此操作。 问题是,当第二次编辑表单时,如果用户没有选择文件,则文件每次都会设置为 NULL。
人们有什么不同的方式来克服这个问题。
我不能将
- 图像存储在数据库中,而是存储在文件系统上(不可能,因为该数据也来自外部 API)
- 将我的视图更改为具有单独的表单来编辑图像?
我已经读过 EF4 Code First:如何仅更新特定字段 http://social .msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/81a0ee7d-bbe1-416c-9d84-7a30e04730fa/
我真正想要的是一种排除字段更新的方法?这是我可以用下面的代码做到这一点的唯一方法吗?或者有更好的方法吗?
public ActionResult Edit(CruiselineEditModel cruiseline, HttpPostedFileBase LogoData)
{
if (ModelState.IsValid)
{
var cl = Mapper.Map<CruiselineEditModel, Cruiseline>(cruiseline);
Cruiseline orgObj = _cl.GetById(cruiseline.Id);
UpdateModel<Cruiseline>(orgObj, "", null, new string[] { "LogoData" });
if (LogoData != null && LogoData.ContentLength > 0)
{
byte[] imgBinaryData = new byte[LogoData.ContentLength];
int readresult = LogoData.InputStream.Read(imgBinaryData, 0, LogoData.ContentLength);
orgObj.LogoData = imgBinaryData;
}
_cl.Save();
}
return View(cruiseline);
}
Using EF4 Codefirst RC and MVC .NET
I have a Strongly typed view I use to for my Insert/Update operations on my Model.
One of the field is a file/Image which is uploaded. I use the below code to do this.
Problem is when editing the form the 2nd time if the user does not select a file the File is set to NULL each time.
What different ways to people over come this.
I can
- Not store the image in the DB but on the file system (no possible as since this data is coming from an external API also)
- Change my View to have a separate form for editing images?
I have already read
EF4 Code First: how to update specific fields only
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/81a0ee7d-bbe1-416c-9d84-7a30e04730fa/
and what I really would like is a way to Exclude a field from being updated? Is the only way I can do that with the code below? or is there a nicer way?
public ActionResult Edit(CruiselineEditModel cruiseline, HttpPostedFileBase LogoData)
{
if (ModelState.IsValid)
{
var cl = Mapper.Map<CruiselineEditModel, Cruiseline>(cruiseline);
Cruiseline orgObj = _cl.GetById(cruiseline.Id);
UpdateModel<Cruiseline>(orgObj, "", null, new string[] { "LogoData" });
if (LogoData != null && LogoData.ContentLength > 0)
{
byte[] imgBinaryData = new byte[LogoData.ContentLength];
int readresult = LogoData.InputStream.Read(imgBinaryData, 0, LogoData.ContentLength);
orgObj.LogoData = imgBinaryData;
}
_cl.Save();
}
return View(cruiseline);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个输入ViewModel,然后您可以在视图模型上有单独的注释。因此,在获取时,将实体映射到视图模型,在发布时将视图模型映射到实体。这将使您在处理此类问题时更加灵活。
Create an input ViewModel, then you can have separate annotations on the view model. So, on the get, map entity to view model, on the post map view model to entity. This will give you more flexibility in dealing with issues like this.