Friday, 8 August 2014

File Upload and Displaying Them as Thumbnails in DataList in MVC3 By Using Razor, C#.Net

8/08/2014 - By Pranav Singh 3

This article will show you how you can upload and save the file in asp.net mvc using razor engine and display the saved data into DataList. So For this article I have used fileupload, MVC, and c#.net. This article you can use in MVC2, MVC3, MVC4, MVC5.


So for this article first we will create a new asp.net mvc application and add input file upload control.
Now we will create mode class and add the below code

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

namespace ProjectDemo_MVC.Models
{
    public class FileListModel
    {
        public List<FileList> FileListCollction { getset; }
        public FileList FileListDetail { getset; }
    }
    public class FileList
    {
        public string Id { getset; }
        public string FileURL { getset; }
        public string FileType { getset; }
        public string Detail { getset; }
    }
}

After creating model we will add out table into out entity file.


After adding all the controls your html will look as shown below.

@model ProjectDemo_MVC.Models.FileListModel
@{
    ViewBag.Title = "File Upload and Displaying Them as Thumbnails in DataList in MVC3 By Using Razor, C#.Net";
}
<style>
    .container
    {
        width: 100%;
        text-align: center;
    }
    .left
    {
        float: left;
        width: 150px;
    }
</style>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <b><u>File Upload in MVC3 By Using Razor</u></b><br />
        <table width="100%">
            <tr>
                <td>
                    Detail :
                </td>
                <td>
                    @Html.TextBoxFor(m => m.FileListDetail.Detail)
                </td>
            </tr>
            <tr>
                <td>
                    Select File :
                </td>
                <td>
                    <input type="file" name="file" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Upload Image" name="Command" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div style="color: Red;">
                        @ViewBag.Message
                    </div>
                </td>
            </tr>
        </table>
        <div class="container">
            @{
                   foreach (var item in Model.FileListCollction)
                   {
                <div class="left">
                    <table width="100%">
                        <tr>
                            <td align="center">
                                @switch (item.FileType)
                                {
                                    case ".jpg": <img src="@item.FileURL" width="100px" height="100px" />
                                                      break;
                                    case ".png": <img src="@item.FileURL" width="100px" height="100px" />
                                                      break;
                                    case ".doc": <img src="../../Icons/doc.png" width="100px" height="100px" />
                                                      break;
                                    case ".html": <img src="../../Icons/html.png" width="100px" height="100px" />
                                                      break;
                                    case ".pdf": <img src="../../Icons/pdf.png" width="100px" height="100px" />
                                                      break;
                                }
                                <br />
                                @item.Detail
                            </td>
                        </tr>
                        <tr>
                            <td align="center">
                            </td>
                        </tr>
                        <tr>
                            <td align="center">
                            </td>
                        </tr>
                    </table>
                </div>                      
            
                   }
            }
        </div>
    </div>
}


In above code I have generated datalist by using div control. In this div control I have assign a style to make it float left.

Check the below style sheet.

<style>
    .container
    {
        width100%;
        text-aligncenter;
    }
    .left
    {
        floatleft;
        width150px;
    }
</style>

Now we have done just check the controller code.

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

namespace ProjectDemo_MVC.Controllers
{
    public class HomeController : Controller
    {
        ///

        /// File Upload in MVC3 By Using Razor
        ///
        public ActionResult Index()
        {
            FileListModel objfilelistmodel = new FileListModel();
            objfilelistmodel.FileListCollction = new List<FileList>();
            objfilelistmodel.FileListCollction = GetUploadedFileList();
            return View(objfilelistmodel);
        }
        ///

        /// Post method for uploading files
        ///
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, FileListModel objfilelistmodel)
        {
            try
            {
                /*Geting the file name*/
                string filename = System.IO.Path.GetFileName(file.FileName);
                string fileExtention = System.IO.Path.GetExtension(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 */
                FileList _objfilelist = new FileList();
                _objfilelist.Id = Guid.NewGuid().ToString();
                _objfilelist.FileURL = filepathtosave;
                _objfilelist.Detail = objfilelistmodel.FileListDetail.Detail;
                _objfilelist.FileType = fileExtention;
                Save(_objfilelist);
                /*Retrived Data*/
                List<FileList> objfilelist = new List<FileList>();
                objfilelist = GetUploadedFileList();
                objfilelistmodel.FileListCollction = objfilelist;
                ViewBag.Message = "File Uploaded successfully.";
            }
            catch
            {
                ViewBag.Message = "Error while uploading the files.";
            }
            return View(objfilelistmodel);
        }
        public int Save(FileList _objfilelist)
        {
         
                NorthwindEntities objnorthwind = new NorthwindEntities();
                FileCollection objFileCollection = new FileCollection();
                objFileCollection.Id = _objfilelist.Id;
                objFileCollection.Detail = _objfilelist.Detail;
                objFileCollection.FileURL = _objfilelist.FileURL;
                objFileCollection.FileType = _objfilelist.FileType;
                objnorthwind.FileCollections.AddObject(objFileCollection);
                /*Save data to database*/
                objnorthwind.SaveChanges();
                return 1;
        }
        ///

        /// This function will return the Data from DB
        ///
        public List<FileList> GetUploadedFileList()
        {
            List<FileList> objfilelist = new List<FileList>();
            NorthwindEntities objnorthwind = new NorthwindEntities();
            var datacollection = from data in objnorthwind.FileCollections
                                 select data;
            foreach (var item in datacollection)
            {
                objfilelist.Add(new FileList { FileURL = item.FileURL, FileType = item.FileType, Detail = item.Detail });
            }
            return objfilelist;
        }

    }
}

        
In above code I have first retrieved the file name and the file extension of uploaded file, and then I have uploaded the file and after successful upload I have saved the uploaded file detail in database. After saving I have fetched the saved record from database to populate the record to user.

Now run the application and check the output after uploading some files like .jpg, pdf, png etc. After successful upload check the table.


Now here is the final output.


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:

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