Part II. Create sample Asp.Net MVC Application

In this tutorial, we will create a sample Asp.net MVC Application using Visual Studio and understand the basic building blocks of this .Net framework.

Download the latest version of Visual Studio from visualstudio.microsoft.com/downloads

What is MVC?

  • Model View Controller (MVC) is a framework, a Programming architecture where you designed your code in 3 different modules. Model it is where all your logical properties or data are declared. View, it is where you designed or creates your Client user interface, and lastly Controller, it is where you process data and connects the model to view.

MVC Diagram:

ASP.NET Web Application

This sample mvc asp net application will give us idea on basic building blocks of Asp.net MVC.

Naming guide:

Below are the names I used for the function.

  • MVCBasicModel.cs » Name of the Model Class(Located under Models Folder)
  • HomeController.cs » Default controller generated by Visual studio after Creation of new     MVC Application Project(Located under Controller folder)
  • Index.cshtml » Default view for HomeController(Located under Views/Home Folder)

Goal: 

  • Generate data from the database
  • Save in a list with model binding.
  • Pass to view and display in a table

Output Preview:

ASP.NET Web Application

Let’s Start:

You can also visit this article Create your first ASP.NET Web Application.

  1. First, open your Visual Studio. Navigate to File/New and then Choose Project right on top of your Visual Studio IDE.
  • IDE » Integrated Development environment
  1. New Project options will popup. Select Visual C# from the left side panel and Search for ASP.NET Web Application from the right-side panel, then click OK.
  2. After that, select a template, which is MVC, then click ok to proceed.
  3. Congratulation!! You have successfully created your MVC project.

Now let’s create a database and table. There are two ways to create a database; you can use SQL Management Studio or Visual Studio Server Explorer. In this tutorial, I’m going to use Visual Studio Server Explorer.

Note:  You need to have SQL Server installed on your machine to proceed with these steps

You may also visit this article to view a detailed tutorial with an image. How to Create Database using SQL Server object Explorer in Visual Studio.

  1. To open SQL Server Explorer in Visual Studio, navigate to View from the menu bar and click on SQL Server Object Explorer. SQL Server Object Explorer will appear on the left side of your Visual Studio IDE.
  2. Navigate to your local SQL Server. Right-click on the Database folder and then click Add New Database. You can name it whatever you like; for me, I name it as sad_db.
  3. After that, navigate to your local SQL server again, and under that, you can see you’re newly created Database. Open the database and go to the Table. Right-Click on it to see add new Table option.
  4. Then add columns to your table.
  • Id » int
  • Employee_Name » varchar(100)
  • EmpCode » varchar(100)
  • Position » varchar(100)
  • Location » varchar(100)
  1. To manually insert sample data. Right-click on your table again and choose view data.
  • Id » 1
  • Employee_Name » John
  • EmpCode » j-123
  • Position » Cashier
  • Location » Place

And now, let’s proceed with the coding part. Let’s add our model class. From your solution explorer located on the right-side panel of your Visual Studio IDE, please navigate to the Model folder, then right-click on it and select the add option, then select the class. Name it as MVCBasicModel. This model will be used to bind with a list in our controller.

Declare these properties from your MVCBasicModel class:

public class MVCBasicModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Ecode { get; set; }
        public string Position { get; set; }
        public string Location { get; set; }

    }

In our HomeController.cs (Located under the Controller folder from the solution explorer), create a separate function/method that will fetch data from our database and return data as a list. Name it as GetData ();

Note: To view Database Connection String, navigate to SQL Server Object Explorer, right-click on your database and then click properties. Under properties, go down to Connection string, then copy and replace SQL Connection string from the code below.

private List<Models.MVCBasicModel> GetData()
        {
            List<Models.MVCBasicModel> list = new List<Models.MVCBasicModel>();
           using (SqlConnection conn = new SqlConnection("Data Source=Computer Name;Initial           Catalog=sad_db;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
            {
                SqlCommand cmd = new SqlCommand("Select * From Employee", conn);
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    list.Add(new Models.MVCBasicModel
                    {
                        ID = int.Parse(reader["Id"].ToString()),
                        Name = reader["Employee_Name"].ToString(),
                        Ecode = int.Parse(reader["EmpCode"].ToString()),
                        Position = reader["Position"].ToString(),
                        Location = reader["Location"].ToString()
                    });
                }
                reader.Close();
            }
            return list;
        }

Passing data to the View

In your, HomeController Index call our function GetData() to get the data we fetch from our database and return it into our view, which is the index.cshtml located under view/Home Folder

       public ActionResult Index()
        {
            return View(GetData());
        }

Index.cshtml

  • @model IEnumerable<MVCBasic.Models.MVCBasicModel> » to gain access the list we pass from our HomeController
  • Use for each loop to manually fill our data into our table
@model IEnumerable<MVCBasic.Models.MVCBasicModel>
@{
    ViewBag.Title = "Home Page";
}
<div class="jumbotron">
   <table class="table table-bordered">
       <thead>
           <tr>
               <th>ID</th>
               <th>Name</th>
               <th>Employee_code</th>
               <th>Position</th>
               <th>Location</th>
           </tr>
       </thead>

       <tbody>
           @{
               foreach (var data in Model)
               {
               <tr>
                   <th>@data.ID</th>
                   <th>@data.Name</th>
                   <th>@data.Ecode</th>
                   <th>@data.Position</th>
                   <th>@data.Location</th>
               </tr>
               }
           }

       </tbody>
   </table>
</div>

and we’re done.. Thank you for reading. Happy coding!!

Code Summary:

MVCBasicModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCBasic.Models
{
    public class MVCBasicModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Ecode { get; set; }
        public string Position { get; set; }
        public string Location { get; set; }
    }

}

 HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;

namespace MVCBasic.Controllers
{
    public class HomeController : Controller
    {
        Models.MVCBasicModel model = new Models.MVCBasicModel();
        public ActionResult Index()
        {
            return View(GetData());
        }

        private List<Models.MVCBasicModel> GetData()
        {
            List<Models.MVCBasicModel> list = new List<Models.MVCBasicModel>();
            using (SqlConnection conn = new SqlConnection("Data Source=PROG-RA;Initial Catalog=sad_db;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
            {
                SqlCommand cmd = new SqlCommand("Select * From Employee", conn);
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    list.Add(new Models.MVCBasicModel
                    {
                        ID = int.Parse(reader["Id"].ToString()),
                        Name = reader["Employee_Name"].ToString(),
                        Ecode = int.Parse(reader["EmpCode"].ToString()),
                        Position = reader["Position"].ToString(),
                        Location = reader["Location"].ToString()
                    });
                }
                reader.Close();
            }
            return list;
        }    
    }

}

Index.cshtml

@model IEnumerable<MVCBasic.Models.MVCBasicModel>
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
   <table class="table table-bordered">
       <thead>
           <tr>
               <th>ID</th>
               <th>Name</th>
               <th>Employee_code</th>
               <th>Position</th>
               <th>Location</th>
           </tr>
       </thead>
       <tbody>
           @{
               foreach (var data in Model)
               {
               <tr>
                   <th>@data.ID</th>
                   <th>@data.Name</th>
                   <th>@data.Ecode</th>
                   <th>@data.Position</th>
                   <th>@data.Location</th>
               </tr>
               }
           }
       </tbody>
   </table>
</div>