0

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>
Community
  • 1
  • 1
RealityDysfunction
  • 2,609
  • 3
  • 26
  • 53
  • see if you can upload file at least to see if model binding is correct . then apply server side validation . – qwr Jun 03 '13 at 12:55
  • How big is the file you're trying to upload? See if this helps: http://stackoverflow.com/questions/10856240/asp-mvc-file-upload-httppostedfilebase-is-null – Rui Jarimba Jun 03 '13 at 13:09

3 Answers3

1

You are using a wrong overload of the Html.BeginForm helper.

The correct call is this:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{

}

You were calling:

Html.BeginForm(object routeValues)

instead of:

Html.BeginForm(
    string actionName, 
    string controllerName, 
    FormMethod method, 
    object htmlAttributes
)

Look at the generated markup in your browser and you will see the fundamental difference.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Instead of

public ActionResult Create(Photo photo)

Try

public ActionResult Create(Photo photo, HttpPostedFileBase file)

EDIT: Don't forget to set the HTTP method to POST in the view:

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
-1

The file in Model will always give you null. In order to get file :

[HttpPost]
        public ActionResult Create(UserViewModel model, 
FormCollection formCollection, HttpPostedFileBase file){

     /* Your code here */
    if(file==null)
    {
        ModelState.AddModelError("NoFile", "Upload File");
    }
}

Here HttpPostedFileBase file will give you the complete object of file uploaded. You can have check condition on the object file. Don't forget to add the below mentioned validation message in view.

@Html.ValidationMessage("NoFile")
Shalin Jirawla
  • 489
  • 1
  • 5
  • 24
  • Oh no, how many times you will include this `file` argument? He already has it as part of his Photo view model. It's completely redundant to have this file argument and even more completely redundant to have this FormCollection argument. – Darin Dimitrov Jun 03 '13 at 13:05
  • I saw Shalin's method online a lot, but in my case it doesn't apply because then I cannot use the model attribute to verify. – RealityDysfunction Jun 03 '13 at 18:25