Ken-F
Ken-F

Reputation: 152

MVC controller if/else statement

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");
    }

Upvotes: 2

Views: 4300

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109185

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.

Upvotes: 2

John White
John White

Reputation: 715

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

Upvotes: 0

Related Questions