1
我有一個模型與ImagePath和PDFPath屬性。上傳不同的文件類型爲不同的模型屬性
當他們點擊保存時,它會在控制器中調用POST操作方法。我需要檢查他們是否只上傳圖像文件和PDF文件。如果他們比上傳的文件類型,這些以外的東西我想設置的ModelState錯誤有以下:
ModelState.AddModelError("ImagePath", "Only image files are accepted");
ModelState.SetModelValue("ImagePath", new ValueProviderResult(null, null, null));
的問題是我需要設置在AddModelError正確的屬性。問題在於它們可能會在ImagePath或PDFPath中放置一個* .doc文件,因此我不知道哪一個報告爲錯誤字段。
我該如何確保他們只上傳角蛋白文件類型?正則表達式?
謝謝
編輯:這是我的控制器代碼。
[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");
}
什麼是ImagePath的(和PDFPath)的財產?它是一個文本框或? – 2009-06-23 15:51:32
是的。 – Jon 2009-06-23 18:40:27