ASP.NET MVC– Display the contents of a CSV file in a Telerik Grid

In this article I’m going to show you how to build an ASP.NET MVC web application that will allow you to upload a CSV file and display the results in a Telerik Grid. We’re going to be using two libraries to help us with this task.

Let’s start by downloading and installing the Telerik Extensions, you can either download a free trial or use the open source version of the extensions. Be sure to read the license on the open source version before using it in your applications.

The library add a Visual Studio extension  as well as new project types. This makes it very easy to use the Telerik extensions in a new project.

After downloading and installing the extensions, let’ go ahead and create a new Visual Studio ASP.NET MVC3 Web Application called “CsvToGrid”.

image

Because we installed the Telerik Extensions for ASP.NET MVC we should see a new Project Template for Telerik MVC Web Application. Let’s select that.

image

Go through the Telerik Project Configuration Wizard and select all the default options. This will create the project and preconfigure all the necessary settings needed by the extensions. This includes configuration options in the web.config file and referencing JavaScript and css files.

After this let’s go ahead and install LinqToCsv. Right click on the references folder and select “Manage NuGet Packages” then search for “LinqToCsv” and install it.

image

    We need to define a sample csv file. Let’s add a new file called people.csv to our desktop with the following data:

FirstName,LastName,Age,State
John, Smith, 35, CA
Mike, Jones, 29, AZ
Susan, Baldwin, 45, CA
Alex, Johnson, 32, WA

As you can see, it’s a simple comma delimited file that represents people and includes their first name, last name , age and state.

We also need a class to represent this data. Let’s add a Person class to our models folder. Add a new class and name file Person.cs The contents of the file should look like this

public class Person{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string State { get; set; }
}

Now let’s modify the home controllers Index view to include a form an a file upload html control. Replace the contents of the file “Index.cshtml” in the Views/Home folder with the following:

@{

ViewBag.Title = “Home Page”;

}

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

{

<input type=”file” name=”file” />

<input type=”submit” name=”btnSubmit” value=”Upload!”/>

}

Now let’s add some code to the controller so that we can save this file to disk. Let’s replace the action methods in HomeController.cs with the following two action methods:

public ActionResult Index(){

return View();

}

[HttpPost]

public ActionResult Index(HttpPostedFileBase file){
if (file.ContentLength > 0){

var fileName = Path.GetFileName(file.FileName);

var path = Path.Combine(Server.MapPath(“~/App_Data/”), fileName);

file.SaveAs(path);

TempData[“file”] = path;

}

return RedirectToAction(“Grid”);

}

Here we’ve added a second Index action method that takes in an HttpPostFileBase, this object will hold the reference to the uploaded file. Now it’s important to note that the name of the input parameter (“file” in our case) has to match up with the name of the html control. If the names don’t match up, the input parameter will come through as null.

In the action method we copy the file to the App_Data folder then we save the file path in TempData and redirect to a new Action called Grid.

The Grid action method will be responsible for reading data from the csv file and passing it to the view so that it can be rendered in telerik grid.

Add the following using statements to the top of your HomeController class

using CsvToGrid.Models;
using LINQtoCSV;

Now add the Grid action method to the home controller.

public ActionResult Grid()
 {
     string file = TempData["file"] as string;
     if (file == null)
     {
         return RedirectToAction("Index");
     }

     CsvContext cc = new CsvContext();
     List<Person> people = cc.Read<Person>(file).ToList();

     return View(people);

 }

This action method reads the file path from tempdata, then uses LinqToCSV to convert the data in the file to a collection of “Person”. This data I then returned to the view.

In the view we need to show this data as a Telerik Grid. Let’s define the view as a strongly typed view of type List<Person>. Let’s also add the code for the Telerik Grid. The complete view code should be

@model IEnumerable<CsvToGrid.Models.Person>

@{
    ViewBag.Title = "Grid";
}

<h2>Grid</h2>

@(Html.Telerik().Grid(Model).Name("PeopleGrid"))

Run the application by pressing alt-F5. On the home screen select the csv file we created earlier and click the upload button. The data within the csv file should now appear as data in your telerik mvc grid.

image

In part two of this post I’m going to show you how to customize the application so that you deal with csv data that doesn’t include a header row. You can download the complete source code for this demo site here.

Advertisements

6 thoughts on “ASP.NET MVC– Display the contents of a CSV file in a Telerik Grid

  1. I am using mvc2 but is there a way to do this if i don’t install the nugget.
    I have my code like below and it’s not working, please try and correct me.

    public class HomeController : Controller
    {
    public ActionResult Index()
    {

    return View(new GridModel());
    }
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase FileUpload, string Submit)
    {
    List ab = new System.Collections.Generic.List();
    DataTable dt = new DataTable();

    if (FileUpload != null && FileUpload.ContentLength > 0)
    {
    string fileName = Path.GetFileName(FileUpload.FileName);
    string path = Path.Combine(Server.MapPath(“~/App_Data/uploads”), fileName);

    try
    {
    FileUpload.SaveAs(path);
    //Process the CSV file and capture the results to our DataTable place holder
    dt = ProcessCSV(path);
    ViewData[“grid”] = parseFile();
    ViewData[“file”] = “File Rendered”;
    }
    catch (Exception ex)
    {
    //Catch errors
    ViewData[“Feedback”] = ex.Message;
    }
    }
    else
    {
    ViewData[“Feedback”] = “Please select a file”;
    }

    return View(“Index”, ViewData[“dt”]);
    }

    private static DataTable ProcessCSV(string fileName)
    {
    //Set up our variables
    string Feedback = string.Empty;
    string line = string.Empty; //”,”;
    string[] strArray;
    DataTable dt = new DataTable();
    // DataRow row;
    // work out where we should split on comma, but not in a sentence
    Regex r = new Regex(“,(?=(?:[^\”]*\”[^\”]*\”)*(?![^\”]*\”))”);
    //Set the filename in to our stream
    StreamReader sr = new StreamReader(fileName);

    line = sr.ReadLine();
    strArray = r.Split(line);

    return dt;
    }

    [GridAction]
    private List parseFile()
    {
    List fileContent = new System.Collections.Generic.List();
    HttpPostedFileBase fb = Request.Files[0];
    StreamReader sd = new StreamReader(fb.FileName);

    string ln = string.Empty;
    string[] ary = null;
    ln = sd.ReadLine();
    do
    {
    ln = sd.ReadLine();
    ary = ln.Split(‘,’);
    fileContent.Add(new ClsFileContent
    {
    FName = ary[0],
    MName = ary[1],
    LName = ary[2]
    });
    }
    while (ln != string.Empty);
    return fileContent;
    }

    The View:

    Index

    Index

    <%=Html.Telerik().Grid((List)ViewData[“grid”])
    .Name(“grid1”).Pageable()
    .Groupable()
    .Filterable()

    %>

    I really need some one to correct me.

    • Deji – If you’re on Visual Studio 2010, you can still use nuget with an MVC2 project. You just have to make sure nuget is installed via the extension manager.

      If you are on Visual Studio 2008 you can still use linq to csv, you just have to download the file manually from here
      http://linqtocsv.codeplex.com/
      After that go the references tab and browse to the folder where you downloaded and extracted the files. Add a reference to LINQtoCSV.dll.

      I would also use a strongly typed collection instead of a DataTable. In the ParseCSV method, you can put the results of the file stream into a List or even a string array.

      In the parsefile method instead of
      List fileContent = new System.Collections.Generic.List();

      try

      List fileContent= new List();

      this would require a strongly typed model of FileContent. See the example in the article above. I created a model called Person and put the results of the csv parsing into a List.

  2. How can this be done in asp.net mvc 2 since I can’t get “Manage Nugget Packages” on the reference. I have got an abandoned work to complete with this feature and i use MVC 2.

    • Sarah – Can you use Visual Studio 2010? VS2010 supports asp.net mvc 2 projects and nuget is available. If you have VS2010 you can install nuget from the VIsual Studio extension manager under the tools file menu.

      If you are on Visual Studio 2008 you can still use linq to csv, you just have to download the file manually from here
      http://linqtocsv.codeplex.com/

      After that go the references tab and browse to the folder where you downloaded and extracted the files. Add a reference to LINQtoCSV.dll.

      Everything else is the same. Good luck!

      • Thanks Hattan,
        How can I validate and handle error if the data in an EMAIL field in the csv file is not a valid email address.

        I have up to 80,000 rows. and it will be strenious to be looking for error on each row manually. How can I validate and track all row record to know the line having error.

      • Like, Look at your telerik grid example on the post. if the value of the State field on line 51,340 is an int value instead abbreviation of US states. i want the app to print the very line and column of the error on the screen.

        Even if there are more then one error, the process should be able to list all error. I look forward to your response Hattan.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s