Click here to Skip to main content
15,886,584 members
Articles / Web Development / HTML
Article

Scaffolding in ASP.NET MVC with DataTable

Rate me:
Please Sign up or sign in to vote.
4.25/5 (7 votes)
30 Oct 2014CPOL3 min read 42.2K   456   12   6
This is a demonstration of ASP.NET MVC Scaffolding with DataTable to store data.

Image 1

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:

Image 2

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

Image 3

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:

Image 4

The model data is represented by the following model class:

C#
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:

Image 5

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

Image 6

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

C#
static DataTable dt = new DataTable();

The following constructor defines the structure of the datatable:

C#
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:

C#
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:

Image 7

Following is the output of the index view:

Image 8

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:

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

The above code displays a Create view as follows:

Image 9

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

C#
[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:

C#
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:

Image 10

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

C#
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:

Image 11

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

C#
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:

Image 12

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

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
GeneralMy vote of 1 Pin
eric hexter31-Oct-14 8:21
eric hexter31-Oct-14 8:21 
GeneralRe: My vote of 1 Pin
Azim Zahir31-Oct-14 17:13
Azim Zahir31-Oct-14 17:13 
Questionhow to store to database? Pin
Cheung Tat Ming31-Oct-14 0:22
Cheung Tat Ming31-Oct-14 0:22 
AnswerRe: how to store to database? Pin
Azim Zahir31-Oct-14 4:51
Azim Zahir31-Oct-14 4:51 
GeneralRe: how to store to database? Pin
Cheung Tat Ming31-Oct-14 5:01
Cheung Tat Ming31-Oct-14 5:01 
GeneralRe: how to store to database? Pin
Azim Zahir1-Nov-14 0:34
Azim Zahir1-Nov-14 0:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.