我有一个要求,当用户上传照片时,我需要在文件大小超过 2mb 时在 View 上显示错误消息。我面临的挑战是除非完全上传照片,否则无法知道照片的大小。(如果可以,请告诉我)。所以一旦文件上传我就失去了我的观点,所以为了在同一个 View 上显示消息什么我应该怎么做?或者如果我可以通过一些 Jquery 弹出窗口显示消息,那也可以满足需要(但是如何从 mvc Controller 调用它?我们可以在用户单击提交按钮后在客户端检查文件大小)。如何继续这?
[HttpPost]
public ActionResult Index(BackgroundImage image)
{
if (image != null && image.File.ContentLength > 0)
{
var fileName = Path.GetFileName(image.File.FileName);
if (image.File.ContentLength > 2080)
{
// need to show error on view or show pop message on client side
}
var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);
image.File.SaveAs(path);
}
return this.RedirectToAction("Index", "ItemDataPhoto", new { id = image.backGroundId });
}
最佳答案
您可以向模型状态添加错误并返回 View 。
if (image.File.ContentLength > 2080)
{
ModelState.AddModelError(string.Empty,"File size is too big");
return View();
}
确保您在 View 中使用 ValidationSummary
助手来显示错误消息。
@Html.ValidationSummary(false)
关于javascript - 用户上传的文件超过大小限制后如何在 View 上显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38503184/