Monday, 16 June 2014

File Upload in MVC3 By Using Razor

6/16/2014 - By Pranav Singh 3

In this article I will show you how you can upload file in mvc3 using razor view engine. This article will provide code for uploading file in asp.net mvc.



So for this article first we will create a new mvc application and add input button and input file control. After adding the controls you view will look as shown below.

@{
    ViewBag.Title = "File Upload in MVC3 By Using Razor";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
    <b><u>File Upload in MVC3 By Using Razor</u></b>
        Select Image
        <input type="file" name="file" />&nbsp;&nbsp;&nbsp;
        <input type="submit" value="Upload Image" name="Command" /><br />
    </div>
    <div>
    @ViewBag.Message
    </div>
}


In above code we have added an attribute in Form tag which is new { enctype = "multipart/form-data" }. This attribute help on finding the uploaded file at controller end when postback will take place.

Now we will check out controller. In our controller we will create a post method by adding the [HttpPost] attribute. Now add the upload code as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ProjectDemo_MVC.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// File Upload in MVC3 By Using Razor
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// Post method for uploading files
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            try
            {
                /*Geting the file name*/
                string filename = System.IO.Path.GetFileName(file.FileName);
                /*Saving the file in server folder*/
                file.SaveAs(Server.MapPath("~/Images/" + filename));
                string filepathtosave = "Images/" + filename;
                /*
                 * HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE
                 *
                 */

                ViewBag.Message = "File Uploaded successfully.";
            }
            catch
            {
                ViewBag.Message = "Error while uploading the files.";
            }
            return View();
        }

    }
}

In above code we are uploading selected file in an Images name folder. So we will create a new folder with name of “Images”. 


Now we have done. Run the application for uploading the file.


Now click on browse button to select file




Now click on upload button your break point will hit and you will get the uploaded file detail in controller 

 

Now press F5 and execute the break point


Now you check the Images folder you will get the uploaded file


DOWNLOAD

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

3 comments:

  1. It gives Null reference Error for some Reason

    ReplyDelete
    Replies
    1. Hi,
      At which point it's giving null reference error...
      There may be a possibility that you have not added your form tag properly. have a look the below

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

      In above new { enctype = "multipart/form-data" } line is very important for file upload in mvc.

      Delete
    2. What if I add form on the layout page and file uploader on view page. I think we get null object.

      Delete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top