Tuesday, 1 June 2021

Upload and display CSV file data in GridView in ASP.Net MVC

In this demo,
1. We will upload a CSV file, and after uploading the record display on the page.
2. Using search, we will search in the uploaded record.

Note: - In the demo, using the in-memory object to store & retrieve the record. You can use a database.

Let's Start

Step 1: - Open
Visual Studio 2015 => Go to File Menu => New => Project...
 
Step 2: - In the Installed Templates list, select Visual C# => Web
 
Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type MVCApplication in the Name box => Click OK
 
Step 4: - Select MVC template from ASP.NET Templates List => Click OK
 
Step 5: - Right Click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type UploadViewModels.cs in the Name box => Click Add
 
Copy Past following code in UploadViewModels.cs
 
public class UploadViewModels
{
    [Required]
    [DisplayName("Browse File")]
    public HttpPostedFileBase BrowseFile { get; set; }
    public string Search { get; set; }
}
 
Step 6: - Right Click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type StudentModels.cs in the Name box => Click Add
 
Copy Past following code in StudentModels.cs
 
public class StudentModels
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string DOB { get; set; }
}
 
Step 7: - Right Click on Controllers folder => Add => Controller... => Select MVC 5 Controller - Empty => Click Add => Type UploadController in Controller Name box => Click Add
 
Copy Past following code in UploadController.cs
 
using MVCApplication.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
 
namespace MVCApplication.Controllers
{
    public class UploadController : Controller
    {
        static List<StudentModels> listStudent = new List<StudentModels>();
 
        public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Index(UploadViewModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    byte[] buffer = new byte[model.BrowseFile.InputStream.Length];
                    model.BrowseFile.InputStream.Seek(0, SeekOrigin.Begin);
                    model.BrowseFile.InputStream.Read(buffer, 0, Convert.ToInt32(model.BrowseFile.InputStream.Length));
                    Stream stream = new MemoryStream(buffer);
                    using (TextReader textReader = new StreamReader(stream))
                    {
                        string line;
                        while ((line = textReader.ReadLine()) != null)
                        {
                            //Here you can write the database insert code
                            string[] result = line.Split(',');
 
                            listStudent.Add(new StudentModels()
                            {
                                Name = result[0],
                                Age = result[1],
                                DOB = result[2]
                            });
                        }
                        ModelState.AddModelError("Meesage", "File uploaded successfully.");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Meesage", ex);
            }
            return View();
        }
 
        [ChildActionOnly]
        public ActionResult ViewUploadedData()
        {
            //Here you can write the database select code
            return PartialView("_ViewUploadedData", listStudent);
        }
 
        [HttpPost]
        public ActionResult Search(string name)
        {
            //Here you can write the database select code
            if (!string.IsNullOrEmpty(name))
            {
                return PartialView("_ViewUploadedData", listStudent.Where(m => m.Name == name).ToList());
            }
            return PartialView("_ViewUploadedData", listStudent);
        }
    }
}
 
Step 8: - Build Project
 
Step 9: - To Add View for Action Method, Right Click inside the Index Action body => Click Add View… => Type Index in the View name box => Click Add
 


 
















Copy Past following code in Index.cshtml
 
@model MVCApplication.Models.UploadViewModels
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
 
@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
 
    <table>
        <tr>
            <td>
                @Html.LabelFor(model => model.BrowseFile, htmlAttributes: new { @class = "control-label col-md-2" })
            </td>
            <td>
                <input name="BrowseFile" type="file" class="form-control" />
                @Html.ValidationMessageFor(model => model.BrowseFile, "", new { @class = "text-danger" })
            </td>
            <td>
                <input type="submit" value="Upload" class="btn btn-default" />
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.Search, htmlAttributes: new { @class = "control-label col-md-2" })
            </td>
            <td>
                @Html.EditorFor(model => model.Search, new { htmlAttributes = new { @class = "form-control" } })
            </td>
            <td>
                <input type="button" value="Search" id="btnSearch" class="btn btn-default" />
            </td>
        </tr>
        <tr>
            <td colspan="3">
                @Html.ValidationMessage("Meesage", "", new { @class = "text-danger" })
            </td>
        </tr>
    </table>
}
<hr />
<div id="dvViewUploadData">
    @{
        Html.RenderAction("ViewUploadedData");
    }
</div>
 
@section Scripts
{
    <script>
        $(document).on("click", "#btnSearch", function () {
            $.post("/Upload/Search", { "name": $("#Search").val() }, function (data, textStatus, jqXHR) {
                $("#dvViewUploadData").empty();
                $("#dvViewUploadData").html(data);
            });
        })
    </script>
}
 
 
Step 10: - Expand View folder => Right Click on Upload folder => Add => View… => Type _ViewUploadedData in the View name box => Checked Create as a partial view checkbox => Click Add
 


 




















Copy Past following code in _ViewUploadedData.cshtml
 
@model IEnumerable<MVCApplication.Models.StudentModels>
 
<h3>Using Table</h3>
<table border="1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DOB)
        </th>
    </tr>
 
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.DOB)
            </td>
        </tr>
    }
</table>
<h3>Using WebGrid</h3>
@{
    var webGrid = new WebGrid(Model, canPage: false);
}
@webGrid.GetHtml();
 
ALL Done
 
RUN Project

Note:- CSS & script rendering from the main application. Use jquery CDN URL to test script.

Output

Copy sample data in a text file and save as .csv

Ram,25,01-Jun-1988,
Shyam,20,01-Jul-1988,
Ghanshyam,30,01-Aug-1988,
Gopal,28,01-Sep-1988,





No comments:

Post a Comment