我有一个与数据一起提交的 MVC 表单。提交后,它会进入预览 View 表单,用户可以在其中决定是否继续发布或再次编辑表单。
除了提交数据之外,我还提供上传图片的选项。我在这个预览表单中基本上有 3 个场景:
- 更新表单并保留现有图片
- 更新表单并替换(或删除)现有图片
- 更新表单并添加图片(如果之前没有)
现在,场景 2) 和 3) 工作正常,但我遇到的是场景 1)。由于某种原因,任何现有图片(来自初始提交)都将被覆盖/删除。当我尝试调试时,我注意到 if 语句的 else 子句被简单地跳过。
我怀疑这与我的 View 或模型有关,因此我发布了我的 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");
}
最佳答案
如果将实体标记为已修改 (.State = EntityState.Modified
),则其所有映射标量属性(即非导航属性)都将成为 SQL 更新语句的一部分。但是,可以从更新中排除选定的属性。操作方法如下:
...
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();
如您所见,您现在可以无条件分配 errand.Picture = imageBytes
:稍后当不需要更新时它将被排除。在(大概)没有更新图片的最常见情况下,这还可以节省更新任务的带宽。
关于c# - MVC Controller if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49696380/