使用数据批注验证viewmodel的各个属性

时间:2012-08-21 11:24:48

标签: c# asp.net-mvc-3 data-annotations asp.net-mvc-viewmodel

我正在尝试使用视图模型和数据注释构建多个文件上载。以下是视图模型:

 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; }
        }

问题: 在这里,我想检查各个属性的模型状态,以显示单个验证错误中的错误。我不知道要检查个人,而对于所有viewmodel我们使用 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
            }

2 个答案:

答案 0 :(得分:0)

如果要返回错误消息,则需要检查Isvalid:

  [HttpPost]
  public ActionResult Index(UploadNewsModel newsmodel)
{
    // If not Valid
    if (!ModelState.IsValid)
    {
       return this.View(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);
}

这样它应该只显示发布文件的错误; 如果要填充所有5个字段,则需要添加[必需]:

[Required]
     [File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
          public HttpPostedFileBase SportNews { get; set; }

**您将无法单独检查每个属性以进行验证,但使用isValid,您将通知用户不正确的文件。

答案 1 :(得分:0)

您的UploadNewsModel没有Username / Password的任何属性,那么您从何处获得这些属性?

如果您只想允许授权访问您的控制器操作,那么您应该使用AuthorizeAttribute

[HttpPost]  
[Authorize]
public ActionResult Index(UploadNewsModel newsmodel)
{
    ...
}