1

I have a couple of files I need to save in addition to some simple scalar data. Is there a way for me to validate that the files have been sent along with the rest of the form data? I'm trying to use the [Required] attribute, but it doesn't seem to be working.

Major Productions
  • 5,914
  • 13
  • 70
  • 149

1 Answers1

7

The following worked for me.

Model:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var fileName = Path.GetFileName(model.File.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
        model.File.SaveAs(path);
        return RedirectToAction("Index");
    }
}

View:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="file" />    
    <%= Html.ValidationMessageFor(x => x.File) %>
    <input type="submit" value="OK" />
<% } %>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • How do you validate specific file types? I.e only allow '.jpg'. – marvc1 Jan 22 '13 at 12:37
  • 1
    You could write a custom validation attribute as I illustrated here: http://stackoverflow.com/a/6388927/29407 which will check whether the uploaded file is an image of a specified type. In my example I showed how this could be done with PNG files but you could very easily adapt this code and make it more generic to accept any other image types. – Darin Dimitrov Jan 22 '13 at 12:40