我正在尝试使用视图模型和数据注释构建多个文件上传。以下是视图模型:
public class UploadNewsModel
{
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase GenearlNews { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase SportNews { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase BusiNews { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase InterNews { get; set; }
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase EntertaintNews { get; set; }
}
问题: 在这里,我想检查单个属性的模型状态以显示单个验证错误中的错误。我不知道要检查个人,而对于我们使用ModelState.IsValid的所有视图模型,我有以下操作:
[HttpPost]
public ActionResult Index(UploadNewsModel newsmodel)
{
HttpPostedFileBase general = newsmodel.GenearlNews;
HttpPostedFileBase sport = newsmodel.SportNews;
HttpPostedFileBase business = newsmodel.BusiNews;
HttpPostedFileBase international = newsmodel.InterNews;
HttpPostedFileBase entertainment = newsmodel.EntertaintNews;
if (general.ContentLength > 0 && general != null && ...check generalnews validation using data annotation == valid.. )
{
var fileName = Path.GetFileName(general.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/News/General News/"), fileName);
general.SaveAs(path);
}
else
{
.... add error of data annotation plus below
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
......... same for remaining upload file
return View(newsmodel);
}
看法:
@model IVRControlPanel.Models.UploadNewsModel
@using (Html.BeginForm("index", "NewsUpload", FormMethod.Post, new { name = "form1", @id = "form1", enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.GenearlNews, new { type = "file" })
@Html.ValidationMessageFor(model => model.GenearlNews)
........... same for remaining file upload
}