2012-04-10 65 views
1

我有一個表單,我上傳兩個圖像。我想對這些圖像進行驗證,例如圖像大小,我希望能夠檢查圖像字段是否未留空。MVC 3圖像字段驗證

public ActionResult Create(NewsViewModel newsViewModel, IEnumerable<HttpPostedFileBase> files) 
    { 
     try 
     { 
      //more code here 

      var originalFile = string.Empty; 

      IList<string> images = new List<string>(2); 

      foreach (var file in files) 
      { 
       if (file != null && file.ContentLength > 0) 
       { 
        var fileName = Path.GetFileName(file.FileName); 
        if (fileName != null) originalFile = Path.Combine(Server.MapPath(upload_path), DateTime.Now.Ticks+"_ "+ fileName); 
        file.SaveAs(originalFile); 

        images.Add(originalFile); 
       } 
      } 

      if (images.Count == 2) 
      { 
       newsViewModel.News.Thumbnail = images[0] ?? ""; 
       newsViewModel.News.Image = images[1] ?? ""; 
      } 
      //more code here 

      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

如何在查看圖像大小並發現它們無效後將響應發送回窗體?

或者如果images.count不是2,我該如何驗證?

有什麼想法?

+0

可能重複的[如何驗證上傳的文件在ASP.NET MVC中?](http://stackoverflow.com/questions/6388812/how-to-validate-uploaded-file-in-asp-net-mvc) – StriplingWarrior 2012-04-10 14:28:25

回答

3

你可以添加一個錯誤的ModelState中,然後重新顯示了同樣的觀點,這樣的事情:在視圖

ModelState.AddModelError(string.Empty, "The image is not valid becuase..."); 
return View(newsViewModel) 

然後,如果你有一個ValidationSummary您的驗證錯誤消息將在其上顯示(第一個參數是與控件ID相匹配的「鍵」,以便通常顯示消息,這就是爲什麼它在這裏是String.empty,但也許你有一個你希望它與之關聯的控件)。

+0

我會補充說,在保存任何內容之前,您應該進行檢查並拒絕提交** - 全部或全部完成。 – 2012-04-10 15:43:16