我正在按照这里的帖子上传和图像并验证其有效性: 如何在 ASP.NET MVC 中验证上传的文件? 但是,我的示例略有不同,因为我不仅接收文件,还接收模型的一些属性。但是,我的验证器总是触发,我调试并发现我的文件总是为空,所以验证器总是触发'false'。我不明白为什么,我的观点似乎是正确的。有任何想法吗?
namespace PhotoManagement.Models
{
public class Photo
{
public virtual int PhotoId { get; set; }
public virtual int ClientId { get; set; }
public virtual string PhotoDescription { get; set; }
[ImageValidation(ErrorMessage="Please select a PNG/JPEG image smaller than 10 MB")]
[NotMapped]
public HttpPostedFileBase File { get; set; }
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Photo photo)
{
if (ModelState.IsValid)
{
db.Photos.Add(photo);
db.SaveChanges();
// File upload occurs now
var FilePath = Path.Combine(Server.MapPath("~/App_Data/" + photo.ClientId), photo.PhotoId.ToString());
photo.File.SaveAs(FilePath);
return RedirectToAction("Create");
}
else return View();
}
@using (Html.BeginForm(new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Photo for @Session["Name"]</legend>
<div class="editor-field">
@Html.Hidden("ClientId",(int)Session["UserId"])
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhotoDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhotoDescription)
@Html.ValidationMessageFor(model => model.PhotoDescription)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.File)
</div>
<div class="editor-field">
<input type="file" name="File" id="File"/>
@Html.ValidationMessageFor(model => model.File)
</div>