Saturday, 31 March 2012

MVC2 upload file via model

I have been wondering about binding upload file using model in ASP.NET MVC2 or MVC3

Usual implementation that I have seen in controller is using HttpPostedFileBase, that exposes the file(s) from request to the user where implementation can be as follows

public ActionResult AcceptFile(HttpPostedFileBase submittedFile)
        {
            var inputStream = submittedFile.InputStream;
            var contentLenght = submittedFile.ContentLength;
            var fileName = submittedFile.FileName;
            var contentType = submittedFile.ContentType;
            return View();
        }


The alternative is using classic upload example where possible implementation can be:

public ActionResult UploadFile(HttpPostedFileBase uploadFile)
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                                               Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
            }
            return View();
        }


So after little research I came out with following implementation as I wanted to have one implementation which i can use in more places, without the code repetition.

I can add custom model binders into Global.asax


ModelBinders.Binders.Add(typeof(MyCustomBinderModel), new MyCustomBinderModel());

after this will be looking like:


protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    ModelBinders.Binders.Add(typeof(MyCustomBinderModel), new MyCustomBinderModel());
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}


and finally the implementation in Controller is


public ActionResult UploadFile(MyCustomBinderModel uploadModel){


  //do your  upload stuff with uploadModel
}