Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Scaffolding in ASP.NET MVC with DataTable

0.00/5 (No votes)
30 Oct 2014 1  
This is a demonstration of ASP.NET MVC Scaffolding with DataTable to store data.

Introduction

ASP.NET Scaffolding is a new feature in ASP.NET MVC, using which you can create data based web applications to interact with a data store and perform add, delete, edit and display operations quickly and without much effort.

Scaffolding automatically generates default templates for listing, displaying, adding, deleting and editing data that can be customized later according to application requirements.

Data can be stored in a variety of locations, for example, database table, data table, XML files or even plain text files. In this article, I am demonstrating the working of ASP.NET MVC scaffolding using a data table.

Background

An MVC application consists of the following components:

  • Model: A model is a class which represents the data and implements logic for data handling.
  • View: A view displays the user interface for an application based on the model class. Using a view, a user can add, delete or edit data.
  • Controller: A controller manages the data entered by a user and controls which views are to be displayed to a user depending on the data.

Using the Code

An ASP.NET MVC application can be created by selecting the 'ASP.NET MVC 4 Web Application' template from the New Project dialog box as follows:

An empty project can be created by selecting the empty template from the resulting dialog box as follows:

A model class called Person is added by right clicking on the Models folder in the solution explorer and selecting the Add option as follows:

The model data is represented by the following model class:

public class Person
{
    public int Code
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
    public int Age
    {
        get;
        set;
    }
}

A controller called PersonController is added by right clicking on the Controllers folder and selecting the Add option as follows:

From the Add Controller dialog box, we choose the 'MVC Controller with empty read/write actions' Template in the Scaffolding options as follows:

The following class level declaration in the controller class (PersonController) creates a static datatable object to store the model data:

static DataTable dt = new DataTable();

The following constructor defines the structure of the datatable:

public PersonController()
{
    if (dt.Columns.Count == 0) // if no columns defined
    {
        dt.Columns.Add(new DataColumn("Code", typeof(int))); // Adding column for the Code attribute
        dt.Columns.Add(new DataColumn("Name", typeof(string))); // Adding column for the Name attribute
        dt.Columns.Add(new DataColumn("Age", typeof(int))); // Adding column for the Age attribute
        DataColumn[] pk = new DataColumn[1];
        pk[0] = dt.Columns[0]; // Specifying Code as the Primary Key
        dt.PrimaryKey = pk;
    }
}

The following Index() action method is used to display a list of Person objects:

public ActionResult Index()
{
    List<Person> lstPerson = new List<Person>(); // Creating a list of Person objects
    foreach (DataRow dr in dt.Rows)
    {
        Person p = new Person(); // Creating a Person object

	// Setting the column values
        p.Code = Convert.ToInt32(dr[0].ToString());
        p.Name = dr[1].ToString();
        p.Age = Convert.ToInt32(dr[2].ToString());

        lstPerson.Add(p); // Populating the list
    }
    return View(lstPerson); // Returning the data to be displayed by the Index view
}

The above code reads data rows from the data table and populates a List object. Then it displays the list through the index view.

The views can be added by right clicking the action method in the controller and selecting the 'Add View' option and choosing the appropriate template from the 'Add View' dialog as follows:

Following is the output of the index view:

To create a new Person object, a Create method with an HttpGet attribute is used. The following Create() method displays the user interface required to create a new Person object:

public ActionResult Create()
{
    return View();
}

The above code displays a Create view as follows:

To save the data entered in the Create view another Create action method with an HttpPost attribute is required as follows:

[HttpPost]
public ActionResult Create(Person p)
{
    DataRow dr = dt.NewRow(); // Creating a new Data Row

    // Setting values for the columns
    dr[0] = p.Code;
    dr[1] = p.Name;
    dr[2] = p.Age;

    dt.Rows.Add(dr); // Adding Data Row to the Data Table
    return RedirectToAction("Index"); // Displaying the index view
}

The above code creates a new data row for the data table, initializes the data in the row using the data entered in the Person object and adds the row to the data table.

In the same way, the following two Edit actions, one with an HttpGet attribute and another with an HttpPost attribute are required to edit Person details:

public ActionResult Edit(int id)
{
    DataRow dr = dt.Rows.Find(id); // Finding Person in the data table using primary key
    Person p = new Person(); // Creating a new Person object

    // Setting attribute values
    p.Code = Convert.ToInt32(dr[0].ToString());
    p.Name = dr[1].ToString();
    p.Age = Convert.ToInt32(dr[2].ToString());

    return View(p); // Returning data
}

[HttpPost]
public ActionResult Edit(int id, Person p)
{
    DataRow dr = dt.Rows.Find(id); // Finding Person

    // Editing data in data row
    dr[0] = p.Code;
    dr[1] = p.Name;
    dr[2] = p.Age;

    return RedirectToAction("Index"); // Displaying the index view
}

Following the Edit view:

The following two functions can be used to delete a Person record:

public ActionResult Delete(int id)
{
    DataRow dr = dt.Rows.Find(id);
    Person p = new Person();
    p.Code = Convert.ToInt32(dr[0].ToString());
    p.Name = dr[1].ToString();
    p.Age = Convert.ToInt32(dr[2].ToString());
    return View(p);
}

[HttpPost]
public ActionResult Delete(int id, Person p)
{
    DataRow dr = dt.Rows.Find(id); // Find Person
    dt.Rows.Remove(dr); // Delete data row
    return RedirectToAction("Index");
}

Following is the Delete view:

A Person record can be displayed using the following Details view:

public ActionResult Details(int id)
{
    DataRow dr = dt.Rows.Find(id);
    Person p = new Person();
    p.Code = Convert.ToInt32(dr[0].ToString());
    p.Name = dr[1].ToString();
    p.Age = Convert.ToInt32(dr[2].ToString());
    return View(p);
}

The above code searches a Person row using the primary key and creates a Person object populated with the values from the row.

Following is the Details view:

The following code in the RouteConfig.cs file is used to specify the default controller and action:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Person", action = "Index", id = UrlParameter.Optional }
    );
}

Points of Interest

I have created the demo project in Microsoft Visual Studio Express 2013 for Web.

This article is a simple demonstration of how scaffolding works. To create a more practical and real world application, you need to store data in a database for persistent storage.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here