I have a form that I upload two images. I want to do validation on these images, such as image size and I want to be able to check if the image field are not left blank.
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();
}
}
How can i send response back to the form after checking the image sizes and find out that they are not valid?
or if images.count is not 2, how do i validate that?
any ideas ?
You could add an error to the ModelState and then re-show the same view, something like this:
Then in the view if you have a ValidationSummary your validation error message would be shown on it (the first argument is the “key” which matches to the control ID to show the message next to usually, which is why it is String.empty here but maybe you have a control you want it to be associated with).