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:
- update form and keep existing picture
- update form and replace (or delete) existing picture
- 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");
}