Wednesday, 26 November 2014

File upload using Model Binding in MVC

I have search through and all solutions are like that there is extra button to upload file
My requirement was to save file on final submit button. I am using model binding to insert data.


 Below is the code to upload file it is very simple and straight forward.

 Model:




















Controller:

     [HttpPost]
        public ActionResult CreateEvent(Models.EventModels e)
        {
            if (ModelState.IsValid)
            {
          int newEventId = eventService.InsertEvent(....);

           if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    if (file != null && file.ContentLength > 0)
                    {
                        string savePath = SaveImage(file, newEventId);
                        eventService.UpdateEventLogo(newEventId, savePath);

                    }
                    }

In the saveImage function save your image in your folder.


View:

    Add enctype attribute in your form

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

    Just add this
    @Html.TextBoxFor(m => m.BaseEvent.Logo, new { type = "file" })

    so after click on final submit button you will get Request.Files object.

No comments:

Post a Comment