我有一个带有addModelError的trry / catch。但它现在正在显示。是的,我已经在该行上设置了一个断点,它已到达该行,但现在显示。
这是actioni方法:
[HttpPost]
public ActionResult EditPhotos(ImageUploadModel ImageUpload)
{
var validImageTypes = new string[]
{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
};
try
{
if (ImageUpload.file == null && ImageUpload.file.ContentLength == 0)
{
ModelState.AddModelError("file", "This field is required");
}
else if (!validImageTypes.Contains(ImageUpload.file.FileName.Substring(ImageUpload.file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("file", "Please upload Your Photo of type: " + string.Join(", ", validImageTypes));
return View(ImageUpload);
}
else if (ImageUpload.file != null && ImageUpload.file.ContentLength > 0)
{
var DirSeparator = Path.DirectorySeparatorChar;
var fileName = Path.GetFileName(ImageUpload.file.FileName);
//var fileName2 = Path.GetFileName(@"\\Cyclist3.jpg");
var path = Server.MapPath(@"\\Images\\profile" + DirSeparator + fileName.Replace('+', '_'));
ImageUpload.file.SaveAs(path);
ViewBag.Message = "File has been uploaded successfully";
ModelState.Clear();
}
}
catch (FileLoadException ex)
{
throw;
}
if (ModelState.IsValid)
{
string username = User.Identity.Name;
// Get the userprofile
UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
// Update fields
byte[] uploadedFile = new byte[ImageUpload.file.ContentLength];
ImageUpload.file.InputStream.Read(uploadedFile, 0, ImageUpload.file.ContentLength);
user.file = uploadedFile;
user.ImageMimeType = ImageUpload.file.ContentType;
db.Entry(user).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
return RedirectToAction("Edit", routeValues: new { controller = "Account", activetab = "tabs-2" });
}
这是观点:
<div class="lifile">
<div id="upload-choices">
<div class="editor-label">
@Html.ValidationMessageFor(model => model.file)
</div>
</div>
</div>
所以例如:
{
ModelState.AddModelError("file", "Please upload Your Photo of type: " + string.Join(", ", validImageTypes));
return View(ImageUpload);
}
我在AddModelError上放了一个断点,它到达那一行,但是没有显示错误。
谢谢
我试过了:
查看:
<div class="lifile">
<div id="upload-choices">
<div class="editor-label">
@Html.ValidationMessageFor(model => model.file)
@Html.ValidationSummary(true)
</div>
</div>
</div>
行动方法
else if (!validImageTypes.Contains(ImageUpload.file.ContentType))
{
ModelState.AddModelError(string.Empty, "Please choose either a GIF, JPG or PNG image.");
return View(ImageUpload);
}
答案 0 :(得分:0)
我相信ModelStateDictionary不会在你的RedirectResult上标记,你应该返回一个ViewResult。
如果在AddModelError行上放置一个断点,那么该行还没有执行。在下一行放置一个断点,错误应该在那里。