Friday, 29 August 2014

FileUpload Control Inside WebGrid To Upload File In Asp.net MVC Using C#.Net

8/29/2014 - By Pranav Singh 5

This article will show you how you can use input fileupload control in an MVC webgrid and the selected file in the controller end inside the webgrid. In this article I have used mvc webgrid and input file control to upload the file when you select in webgrid by using asp.net mvc and c#.net.


So for this article first we will create a new asp.net mvc application and add the model class file in model folder.

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

namespace MvcApplication7.Models
{
    public class StudentModel
    {
        public List<Student> StudentList { get; set; }
    }
    public class Student
    {
        public string Name { get; set; }
        public string UploadFile { get; set; }
        public string Address { get; set; }
    }
}

Now we will add the controller file in controller folder. In this file we will add the below code.

public ActionResult Index()
        {
            StudentModel _objstudentmodel = new StudentModel();
            _objstudentmodel.StudentList = new List<Student>();
            _objstudentmodel.StudentList.Add(new Student { Name = "Name1", Address = "Address1" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name2", Address = "Address2" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name3", Address = "Address3" });
            return View(_objstudentmodel);
        }

In above code on httpget we assign some value to the list collection for displaying on webgrid. Now we will create the view for this controller action.

@model  MvcApplication7.Models.StudentModel
@{
    ViewBag.Title = "WebGrid With FileUpload In Asp.net MVC Using C#.Net";
}
<style type="text/css">
    table
    {
        font-family: verdana,arial,sans-serif;
        font-size: 11px;
        color: #333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }
    table th
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }
    table td
    {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }
</style>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    var grid = new WebGrid(Model.StudentList, canSort: false, canPage: false);
    int rowNum = 0;
    <div>
        @grid.GetHtml(columns:
            grid.Columns
            (
                grid.Column("RowNumber", format: item => rowNum = rowNum + 1),
                grid.Column("", "", format: @<input type="file" name="files" value="" />),
                  grid.Column("Name", format: (item) => Html.TextBox("StudentList[" + (rowNum - 1).ToString() + "].Name", (object)item.Name, new { @style = "width:60px" })),
                 grid.Column("Address", format: (item) => Html.TextBox("StudentList[" + (rowNum - 1).ToString() + "].Address", (object)item.Address, new { @style = "width:60px" }))
            ), mode: WebGridPagerModes.Numeric)
    </div>
    <input type="submit" value="Submit" />
}

In above code I have added grid.Column("", "", format: @< input type="file" name="files" value="" / >) for file upload control. This line of code will display the file upload control in webgrid. Here u must assign the control name, because we will access the control input by name at controller end, and the parameter name and the control name must be same.

After this we will add HTTPPOST method in our controller.

  [HttpPost]
        public ActionResult Index(HttpPostedFileBase[] files, StudentModel _objstudentmodel)
        {
            try
            {
                /*Lopp for multiple files*/
                foreach (HttpPostedFileBase file in files)
                {
                    /*Here we are checking weather file is selected or not
                     *if file is not selected on that case we will get null
                     * in collection for that ro.
                     */
                    if (file != null)
                    {
                        /*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;
                        /*APPEND THE FILE NAME IN COLLECTION*/
                        /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL AND DATA IN DATA BASE*/
                    }
                }

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

In above code please check this parameter HttpPostedFileBase[] files this will show us the collection all the files. If you have not selected any file in gridview row on that case it will show null in collection, so I have checked weather the file is selected for the array index of not , if it selected then i have passed to save the file in folder and in data base.

Note: Here you must take care one thing HttpPostedFileBase parameter variable name and the input file control name must be same. Otherwise you will not be able to get the selected file collection.

So here is the controller complete code.

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

namespace MvcApplication7.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            StudentModel _objstudentmodel = new StudentModel();
            _objstudentmodel.StudentList = new List<Student>();
            _objstudentmodel.StudentList.Add(new Student { Name = "Name1", Address = "Address1" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name2", Address = "Address2" });
            _objstudentmodel.StudentList.Add(new Student { Name = "Name3", Address = "Address3" });
            return View(_objstudentmodel);
        }
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase[] files, StudentModel _objstudentmodel)
        {
            try
            {
                /*Lopp for multiple files*/
                foreach (HttpPostedFileBase file in files)
                {
                    /*Here we are checking weather file is selected or not
                     *if file is not selected on that case we will get null
                     * in collection for that ro.
                     */
                    if (file != null)
                    {
                        /*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;
                        /*APPEND THE FILE NAME IN COLLECTION*/
                        /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL AND DATA IN DATA BASE*/
                    }
                }

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

    }
}

Before running the application we will create a folder where we will upload the file.



Now we have done. Let’s Run the application to check the output. Here are the files which we will upload.


Now here is the webgrid with file upload control.



Now select the file and click on submit button.
As you click on submit your break point will hit and you will get all the selected file.



Here in above image you see that in collection your are getting only those two selected files which you have selected and you are getting null for the third file which you have not selected. now lets check the collection of file weather we have get correct file in collection or not, Have a look of the below image.


Here we are getting the selected file. Now press F5 and check the image folder.



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

5 comments:

  1. Dear Author,

    In Index method

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase[] files, StudentModel _objstudentmodel)
    {
    try
    {
    /*Lopp for multiple files*/
    foreach (HttpPostedFileBase file in files)
    {
    /*Here we are checking weather file is selected or not
    *if file is not selected on that case we will get null
    * in collection for that ro.
    */
    if (file != null)
    {
    /*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;
    /*APPEND THE FILE NAME IN COLLECTION*/
    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL AND DATA IN DATA BASE*/
    }
    }

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

    }

    How could we know which _objstudentmodel is associated with file uploaded? Could you please guide me out how can I match the student object and uploaded file linked?

    Best regards,

    Veasna

    ReplyDelete
    Replies
    1. The sequence of upload file nd student record will be in same sequence.
      So file 1 belongs to the first record of student.

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete

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