ビューモデルとデータ注釈を使用して複数のファイルのアップロードを構築しようとしています。以下はビューモデルです。
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
}