是的,你可以添加ModelState.AddModelError但在你看来,如果你想显示此消息,你应该使用一些HTML佣工如Html.ValidationSummary或Html.ValidationMessage的。
例如,在您的视图:
@Html.ValidationMessage("file")
,并在你的控制器动作:
ModelState.AddModelError("file", "some error message");
显然,这是更好的使用视图模型,这些佣工的强类型的等价物以及使用帮助者生成你的标记,而不是像你的情况那样对它进行硬编码。
你知道,事情就是:
public class MyViewModel
{
[Required(ErrorMessage = "Please select a file first")]
public HttpPostedFileBase File { get; set; }
[Required(ErrorMessage = "Please enter a name")]
public string Title { get; set; }
public string Description { get; set; }
}
,并在您看来的东西,如:
@model MyViewModel
...
@using (Html.BeginForm("Upload", "Picture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(x => x.File, new {
type = "file",
style = "opacity:0",
οnchange="document.getElementById('title').value = this.value.substring(this.value.lastIndexOf('\\') +1);"
})
@Html.ValidationMessageFor(x => x.File)
@Html.EditorFor(x => x.Title)
@Html.ValidationMessageFor(x => x.Title)
@Html.TextAreaFor(x => x.Description)
}
,并在你的控制器动作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
try
{
Image.FromStream(model.File.InputStream);
}
catch (ArgumentException)
{
ModelState.AddModelError("File", "The file you are trying to upload is not a valid image file.");
}
// At this stage you know that the model is valid =>
// you could do something with those model.Title and model.Description properties
return RedirectToAction("Success");
}
通过你可能采取的方式看看following answer of mine从你的控制器动作中删除更多管道/验证代码不属于那里。