I am uploading and image and verifying its validity as per this post here: How to validate uploaded file in ASP.NET MVC? However, my example differs slightly because I am not just receiving the file, I am also receiving some properties for my model. However, my validator always fires, I debugged and found that my file is always null, so validator always fires back 'false'. I don't understand why, my input in view seems to be correct. Any ideas?
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>