开发者

MVC .NET How best to update model with file upload

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);开发者_如何学C
                 orgObj.LogoData = imgBinaryData;
            }
            _cl.Save();                  

        }
        return View(cruiseline);
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜