2

I have a MVC form that is submitted with data. After submit, it goes into a preview view form where a user can decide whether to proceed posting or edit the form again.

Apart from submitting data, I also offer the option to upload a picture. I basically have 3 scenarios in this preview form:

  1. update form and keep existing picture
  2. update form and replace (or delete) existing picture
  3. update form and add a picture (in case there was none before)

Now, scenario 2) and 3) work fine, but what I am struggling with is scenario 1). For some reason any existing picture (from the initial submit) would be overridden/deleted. When I tried to debug I noticed that the else clause of my if statement is simply being skipped.

I doubt this has something to do with my view or the model, hence I am posting the relevant code of my controller.

    public ActionResult UpdateErrand(
        [Bind(Exclude                       = "Picture")]errands model)
    {
        // define variables for reuse
        var userID                          = User.Identity.GetUserId();
        DateTime nowUTC                     = DateTime.Now.ToUniversalTime();
        DateTime nowLocal                   = DateTime.Now.ToLocalTime();
        // get picture and get it to bytes
        string picture                      = Request.Form["editErrandCroppedPicture"];
        byte[] imageBytes                   = Convert.FromBase64String(picture);
        // define errand
        var errand                          = new errands
        {
            // basics
            UserID                          = userID,
            FirstName                       = UserManager.FindById(userID).FirstName,
            Email                           = UserManager.FindById(userID).Email,
            Phone                           = UserManager.FindById(userID).PhoneNumber,
            //Rating                        = 

            // form
            ID                              = model.ID,
            Category                        = model.Category,
            SubCategory                     = model.SubCategory,
            Title                           = model.Title,
            Description                     = model.Description,
            Location                        = model.Location,
            ASAP                            = model.ASAP,
            StartDateTime                   = model.StartDateTime,
            DurationInHours                 = model.DurationInHours,
            EndDateTime                     = model.EndDateTime,
            DateTimePosted                  = nowLocal,
            Currency                        = model.Currency,
            Offering                        = model.Offering,
            Price                           = model.Price,
            errandTax                       = model.errandTax,
            PaymentMethod                   = model.PaymentMethod,
            LatitudePosted                  = model.LatitudePosted,
            LongitudePosted                 = model.LongitudePosted,
            LocationPosted                  = model.LocationPosted,
            Published                       = true
        };
        // workaround to ensure picture is uploaded correctly
        if (imageBytes.Length               > 2)
        {
            errand.Picture                  = imageBytes;
        }
        else
        {
            errand.Picture                  = model.Picture;
        }
        // save errand to DB
        ERRANDOM.Entry(errand).State = EntityState.Modified;
        ERRANDOM.SaveChanges();
        // track user activity: post includes activity name, timestamp along with location, and if authenticated, user ID
        var SUCCESS                         = new UserActivities
        {
            UserID                          = userID,
            ActivityName                    = "EditErrand_Success",
            ActivityTimeStampUTC            = nowUTC,
            ActivityLatitude                = model.LatitudePosted,
            ActivityLongitude               = model.LongitudePosted,
            ActivityLocation                = model.LocationPosted
        };
        ERRANDOM.UserActivityList.Add(SUCCESS);
        ERRANDOM.SaveChanges();
        return RedirectToAction("errandPreview");
    }
1
  • Just a side note, take a look at AutoMapper, maybe it's nice tool for you. Commented Apr 6, 2018 at 16:30

2 Answers 2

2

If you mark an entity as modified (.State = EntityState.Modified) all of its mapped scalar properties (i.e. non-navigation properties) will be part of the SQL update statement. However, it's possible to exclude selected properties from the update. Here's how to do it:

...
LatitudePosted = model.LatitudePosted,
LongitudePosted = model.LongitudePosted,
LocationPosted = model.LocationPosted,
Published = true
errand.Picture = imageBytes;

ERRANDOM.Entry(errand).State = EntityState.Modified;

if (imageBytes.Length <= 2)
{
    ERRANDOM.Entry(errand).Property(e => e.Picture).IsModified = false;
}

ERRANDOM.SaveChanges();

As you see, you can now assign errand.Picture = imageBytes unconditionally: it will be excluded later when it doesn't need updating. This also saves bandwidth in updating errands in the (presumably) most common case when no picture is updated.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh and forgot to mention: maybe Request.Form["editErrandCroppedPicture"] contains the current picture if it exists? That would explain skipping over the else.
yes, Request.Form[...] contains the current picture, if selected and cropped, that is. Just out of curiosity, why would that lead to skipping the else? I mean, if no pic is selected/cropped, the Request.Form[...] would/should be empty...?
What I mean by "current" is your case 1. If that existing image is shown and also returned in Request.Form[...] thenimageBytes.Length is always > 2, isn't it?
0

You are excluding binding Picture so your IF statement else clause would be assigning a null value (model.Picture) to a "new" errands object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.