検証を行いたい (必要なフィールド、長さの検証、利用規約のチェック、ファイル サイズのチェックなど、ファイルが Web サーバーに送信される前に)
ファイルが Web サーバーにアップロードされた後 (2 GB のファイルの場合、たとえば 20 分かかります)、「タイトル」などのフィールドを空のままにしておくと、エラー メッセージが表示されます。
事前に検証を行うにはどうすればよいですか?
意見:
@using (Html.BeginForm("FileUpload", "Home")){
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Video Upload</legend>
<ol>
<li>
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title, new {@Class = "action add", title="Enter your video/movie title here." })
</li>
<li>
@Html.LabelFor(m => m.Description)
@Html.TextAreaFor(m => m.Description, new Dictionary<string,object>{{"rows","3"}})
</li>
<li>
@Html.CheckBoxFor(m => m.AGB)
@Html.LabelFor(m => m.AGB, new {@class = "checkbox" })
</li>
</ol>
<input type="file" id="fileCntrl" name="uploadFile" accept="video/*" data-val="true" data-val-required="File is required"/>
<button type="submit" id="btnUpload" value="Upload Video" title="Upload Video" class="btn">Upload Video</button>
</fieldset>
}
モデル:
public class UploadModel
{
[Required]
[StringLength(100)], ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
[Display(Name = "* Title:")]
public string Title { get; set; }
[StringLength(300)], ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
[Display(Name = "Description:")]
public string Description { get; set; }
[Required]
[Display(Name = "* I agree to mowee.tv Terms And Conditions.")]
public bool AGB { get; set; }
}
コントローラ:
[HttpPost]
[AllowAnonymous]
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult FileUpload(HttpPostedFileBase uploadFile, UploadModel myModel)
{
if (ModelState.IsValid) // **<== i arrive here after file has been submitted to webserver**
{
try
{
if (myModel.AGB == false)
{
ModelState.AddModelError("", "Please read our Terms and Conditions");
return View("Index", myModel);
}
if (uploadFile != null && uploadFile.ContentLength > 0)
{
//write some data to database
//send mail with link for uploaded file
}
else
{
ModelState.AddModelError("", "Please choose a video/movie.");
return View("Index", myModel);
}
}
catch (Exception ex)
{
ModelState.AddModelError("", "An error occured. Try again.");
return View("ErrorUpload", myModel);
}
//model is valid
return View("SuccessUpload", myModel);
}
// model is not valid
return View("Index", myModel);
}