I have a model with ImagePath and PDFPath properties.
When they click save, that calls the POST action method in the controller. I need to check that they have only uploaded image files and pdf files. If they have uploaded something other than these filetypes I want to set a ModelState error with the following:
ModelState.AddModelError("ImagePath", "Only image files are accepted");
ModelState.SetModelValue("ImagePath", new ValueProviderResult(null, null, null));
The problem is I need to set the correct properties in the AddModelError. The problem being they could have put a *.doc file in the ImagePath or PDFPath so I don't know which one to report as the error field.
How do I also make sure that they do only upload ceratin filetypes? RegEx?
Thanks
EDIT: Here is my controller code.
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public ActionResult Create([Bind(Prefix = "", Exclude = "ID")] News item)
{
string imageUrl = "";
string pdfurl = "";
try
{
News.CheckForErrors(item);
}
catch (RulesException ex)
{
ex.AddModelStateErrors(ModelState, null);
}
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("/uploads"), Path.GetFileName(file.FileName));
if (Path.GetExtension(file.FileName).ToLower() != ".jpg" || Path.GetExtension(file.FileName).ToLower() != ".pdf")
{
//HELP! - Which model has the property error ImagePath/PDFPath?
ModelState.AddModelError("ImagePath", "Only JPG image files are accepted");
ModelState.SetModelValue("ImagePath", new ValueProviderResult(null, null, null));
break;
}
imageUrl = "/uploads/" + file.FileName;
}
}
if (!ModelState.IsValid)
{
return View(item);
}
try
{
item.Save(User.Identity.Name);
}
catch (Exception x)
{
}
return RedirectToAction("Index");
}