Create MVC Project Step By Step From Scratch- Part One

Prerequisites

  1. General knowledge on Web Applications.
  2. HTML, CSS, Bootstrap, JavaScripts.
  3. DataBase configuration and connection.

Introduction

We often think creating MVC projects is very hard, as we have to work on each and every part. It's true, as we have to work on each and every part i.e. starting from creating controls to Business layers.

Believe me, if we start understanding the architecture once, it's so easy to implement. Here, we will explain how to create a small MVC demo project from scratch.

Remember, when you work with ASP.NET project or MVC project, we must require the things, mentioned below.

Mvc

Thus, these are the common things that all the projects contain, so I will explain how we can create these things very easily.

Project Goals

This is a simple Web Application, which will track the records of the mobile and its price in India. We have a mobile store. This project will maintain the records of all the mobiles in the store, keep track on the mobile sales, purchases etc. We can also have a facility to check the profit earned by this store monthly and yearly.

Technology Used

  • ASP.NET MVC
  • SQL Server
  • Crystal Report
  • ADO.NET

In this article, we will mainly focus on the areas, mentioned below.

  1. Working with different layers in the project.
  2. Creating DAL logic.
  3. WorkFlow of the project.
  4. Creating different layout for the different users.
  5. Working with Home Page (showing data with the mobile images on Home page)

Let's just start our project. Create a new MVC project, as shown below.

Mvc

Now, choose ASP.NET Web Application.

Mvc

Change the name of the project and add another class library and MobileDAL. Here, we have attached Solution Explorer, as shown below.

Mvc

Now, let's start configuring the database with the project.

Go to web.config and write the connection string, as shown below.

  1. <connectionStrings>  
  2.     <add name="Connect" connectionString="Data Source=*****; User id=****;password=****;Database=Demo" providerName="System.Data.SqlClie nt" /> </connectionStrings>  
From here, let's see the project flow. Here is the complete project flow, which we have given below.

Mvc

Here, the data will pass from View to controller (so all the business logic will be written here) and from the controller, the data will pass to the DAL layer (which is MobileDAL.cs in our case).

Here, Data access layer (DAL) contains all the logic to retrieve the data from the database.

Thus, in our DAL layer, we will have to define the connection string to the database and the core logic to perform DDL and DML operation from the database, as per our requirements.

Now, add a new class as "MobiledetailDAL.cs" in MobileDAL layer and write the functions, mentioned below for establishing the connection with the database and perform DML and DDL operation.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Data;  
  7. using System.Configuration;  
  8. using System.Data.SqlClient;  
  9. namespace MobileDAL.cs {  
  10.     public class MobiledetailDAL {  
  11.         SqlCommand cmd;  
  12.         SqlDataAdapter da;  
  13.         DataSet ds;  
  14.         public static SqlConnection connect() {  
  15.             string connection = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;  
  16.             SqlConnection con = new SqlConnection(connection);  
  17.             if (con.State == ConnectionState.Open) {  
  18.                 con.Close();  
  19.             } else con.Open();  
  20.         }  
  21.         return con;  
  22.     }  
  23.     public bool DMLOpperation(string query) {  
  24.         cmd = new SqlCommand(query, MobiledetailDAL.connect());  
  25.         int x = cmd.ExecuteNonQuery();  
  26.         if (x == 1) {  
  27.             return true;  
  28.         } else {  
  29.             return false;  
  30.         }.  
  31.     }  
  32.     public DataTable SelactAll(string query) {  
  33.         da = new SqlDataAdapter(query, MobiledetailDAL.connect());  
  34.         DataTable dt = new DataTable();  
  35.         da.Fill(dt);  
  36.         return dt;  
  37.     }  
  38. }  
  39. }  
Let's discuss about each and every method, which is present in this class.

The first method is to read the connection string from Web.config.
  1. public static SqlConnection connect() {  
  2.     string connection = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;  
  3.     SqlConnection con = new SqlConnection(connection);  
  4.     if (con.State == ConnectionState.Open) {  
  5.         con.Close();  
  6.     } else {  
  7.         con.Open();  
  8.     }  
  9.     return con;  
  10. }  
First, we have created a static method as "Connect()".

This method is static because we do not want to create an object of the class for calling this method. The first line will read the connection string, which is defined in the web.config in the name of "Connect".

After reading the connection string, it will save the connection string details in a string called "Connection".

Afterwards, we are passing this string to SQL connection to establish the connection.
Subsequently, we are checking the connection state, if the state is open and we are closing the connection, else we are opening the connection.

Now, let's come to the second method.
  1. public bool DMLOpperation(string query) {  
  2.     cmd = new SqlCommand(query, MobiledetailDAL.connect());  
  3.     int x = cmd.ExecuteNonQuery();  
  4.     if (x == 1) {  
  5.         return true;  
  6.     } else {  
  7.         return false;  
  8.     }  
  9. }  
As we have seen the architecture, we will pass the query from controller, which will execute in DAL Layer, this method is written to perform DML opperation(CREAT,UPDATE,etc). So whatever query will be passed from controller, it will come to the methods and be stored in the string query.

Now, we have created a command object. Normally, a command object will take two parameters, as shown below.

Mvc

For the first parameter, we will pass as the string received and for the second parameter, we have call the connection earlier, which we have made in connect method.

Here, I am calling "MobiledetailDAL.connect()" for the connection string. Afterwards, we are executing the command to do our work.

Whenever we will declare, it will work like this.

Now, DAL part is over. Let us start working on some views or screens, so let's design the Layouts.

Layouts are used in MVC to provide consistent look and feel on all the pages of our Application. It is same as the master pages that we have in ASP.NET. We should always create Layout in the shared folder.

To check how to create layout step by step, please follow the link.

The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an Application. The layout view eliminates duplicate coding and enhances the development speed and easy maintenance.

The layout view for the sample UI, mentioned above would contain a header, left menu, right bar and footer sections. It contains a placeholder for the center section, which changes dynamically, as shown below.

Mvc

Thus, let's create a common layout for all the users. I want a left side menu in which my menu items are there, so the code is given below to create the layout.
  1. <script src="~/Scripts/vertical.js"></script>  
  2. <link href="~/Content/VerticalMenu.css" rel="stylesheet" /> @*---Vertical Menu---*@  
  3. <div class="row">  
  4.     <!-- uncomment code for absolute positioning tweek see top comment in css -->  
  5.     <!-- <div class="absolute-wrapper"> </div> -->  
  6.     <!-- Menu -->  
  7.     <div class="side-menu">  
  8.         <nav class="navbar navbar-default" role="navigation">  
  9.             <!-- Brand and toggle get grouped for better mobile display -->  
  10.             <div class="navbar-header">  
  11.                 <div class="brand-wrapper">  
  12.                     <!-- Hamburger --><button type="button" class="navbar-toggle">   
  13. <span class="sr-only">Toggle navigation</span>   
  14. <span class="icon-bar"></span>   
  15. <span class="icon-bar"></span>   
  16. <span class="icon-bar"></span>   
  17. </button>  
  18.                     <!-- Brand -->  
  19.                     <div class="brand-name-wrapper"> <a class="navbar-brand" href="#">   
  20. Brand   
  21. </a> </div>  
  22.                     <!-- Search -->  
  23.                     <a data-toggle="collapse" href="#search" class="btn btn-default" id="search-trigger"> <span class="glyphicon glyphicon-search"></span> </a>  
  24.                     <!-- Search body -->  
  25.                     <div id="search" class="panel-collapse collapse">  
  26.                         <div class="panel-body">  
  27.                             <form class="navbar-form" role="search">  
  28.                                 <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default "><span class="glyphicon glyphicon-ok"></span></button> </form>  
  29.                         </div>  
  30.                     </div>  
  31.                 </div>  
  32.             </div>  
  33.             <!-- Main Menu -->  
  34.             <div class="side-menu-container">  
  35.                 <ul class="nav navbar-nav">  
  36.                     <li><a href="#"><span class="glyphicon glyphicon-user"></span>User Profile</a></li>  
  37.                     <li class="active"><a href="#"><span class="glyphicon glyphicon-home"></span>Home</a></li>  
  38.                     <li><a href="#"><span class="glyphicon glyphicon-envelope"></span> Message Center</a></li>  
  39.                     <li><a href="#"><span class="glyphicon glyphicon-phone"></span> Mobiles</a></li>  
  40.                     <!-- Dropdown-->  
  41.                     <li class="panel panel-default" id="dropdown">  
  42.                         <a data-toggle="collapse" href="#dropdown-lvl1"> <span class="glyphicon glyphicon-cog"></span> Setting <span class="caret"></span> </a>  
  43.                         <!-- Dropdown level 1 -->  
  44.                         <div id="dropdown-lvl1" class="panel-collapse collapse">  
  45.                             <div class="panel-body">  
  46.                                 <ul class="nav navbar-nav">  
  47.                                     <li><a href="#">Link</a></li>  
  48.                                     <li><a href="#">Link</a></li>  
  49.                                     <li><a href="#">Link</a></li>  
  50.                                     <!-- Dropdown level 2 -->  
  51.                                     <li class="panel panel-default" id="dropdown">  
  52.                                         <a data-toggle="collapse" href="#dropdown-lvl2"> <span class="glyphicon glyphicon-off"></span> Sub Level <span class="caret"></span> </a>  
  53.                                         <div id="dropdown-lvl2" class="panel-collapse collapse">  
  54.                                             <div class="panel-body">  
  55.                                                 <ul class="nav navbar-nav">  
  56.                                                     <li><a href="#">Link</a></li>  
  57.                                                     <li><a href="#">Link</a></li>  
  58.                                                     <li><a href="#">Link</a></li>  
  59.                                                 </ul>  
  60.                                             </div>  
  61.                                         </div>  
  62.                                     </li>  
  63.                                 </ul>  
  64.                             </div>  
  65.                         </div>  
  66.                     </li>  
  67.                     <li><a href="#"><span class="glyphicon glyphicon-signal"></span> Link</a></li>  
  68.                 </ul>  
  69.             </div>  
  70.             <!-- /.navbar-collapse -->  
  71.         </nav>  
  72.     </div>  
  73.     <div class="container-fluid">  
  74.         <div class="side-body"> @RenderBody() </div>  
  75.     </div>  
  76. </div>  
RenderBody method in the layout page helps to render child page/view. It is just like the ContentPlaceHolder in master page. A layout page can have only one RenderBody method.

To create menu item, I have taken Bootstrap Glyphions.

Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis to simplicity and easy orientation. If you want to learn more about Glyphicons, please check the link.

A Glyphicon will be used by span tag, as shown below.

<span class="glyphicon glyphicon-name"></span>

The name part in the syntax, mentioned above must be replaced with the proper name of the Glyphicon.

Here are some of Glyphicons

Mvc

NOTE

Please don't worry, as .CSS and .JS are used here. I will upload all these with the project.

Now, let's attach this layout in a view and run the project. Create a view as About and attach it, as shown below.

Mvc

Now, check the view. We will find the layout, which will be attached, as shown below.
  1. @ {  
  2.     ViewBag.Title = "AboutUs";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. } < h2 > About < /h2>  
Now, run the Application.

Mvc

As you see how we can create a layout page in MVC, so I can have a multiple number of layout pages in my project (eg: For registered user, for anonymous user etc).
Lets create one more layout page for the anonymous user.This is HTML code to create simple layout, as shown below.
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>  
  2. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  3. <nav class="navbar navbar-inverse">  
  4.     <div class="container-fluid">  
  5.         <div class="navbar-header"> <a class="navbar-brand" href="#">MoBBi99</a> </div>  
  6.         <ul class="nav navbar-nav">  
  7.             <li class="active"><a href="#">Home</a></li>  
  8.             <li><a href="#">Login</a></li>  
  9.             <li><a href="#">Register</a></li>  
  10.         </ul>  
  11.         <form class="navbar-form navbar-left">  
  12.             <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form>  
  13.     </div>  
  14. </nav>  
  15. <div class="container"> @RenderBody(); </div>  
Lets use this page in the Index page, which is our Home page.
  1. @ {  
  2.     Layout = "~/Views/Shared/_HomepageLayout.cshtml";  
  3. }  
In my Home page, I have to show some mobile products. These products are required to be fetched from the database table with the image. Here is my table script.
  1. USE[Demo]  
  2. GO  
  3. /****** Object:  Table [dbo].[Mobiles]    Script Date: 26-11-2016 22:01:47 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE[dbo].[Mobiles](  
  9.     [slNo][int] IDENTITY(1, 1) NOT NULL, [MobileName][nvarchar](100) NULL, [Price][money] NULL, [url][nvarchar](350) NULL, [Description][text] NULL, CONSTRAINT[PK_Mobiles] PRIMARY KEY CLUSTERED(  
  10.         [slNo] ASC) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]) ON[PRIMARY] TEXTIMAGE_ON[PRIMARY]  
  11. GO  
Now, let's add an Image folder in the Project and add some mobile images, as shown below.

Mvc

Here is my data in the Demo table.

Mvc

Let's create a model as Mobile model, as shown below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace DapperProject.Models {  
  6.     public class Mobiles {  
  7.         public int slno {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string MobileName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public double Price {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Url {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string Description {  
  24.             get;  
  25.             set;  
  26.         }  
  27.     }  
  28. }  
Now, we have the Home Controller with Index method.
  1. public class HomeController: Controller {  
  2.         MobiledetailDAL _mdal = new MobiledetailDAL();  
  3.         DataTable dt;  
  4.         public ActionResult Index() {  
  5.             string mycmd = "select * from Mobiles";  
  6.             dt = new DataTable();  
  7.             dt = _mdal.SelactAll(mycmd);  
  8.             List < Mobiles > list = new List < Mobiles > ();  
  9.             for (int i = 0; i < dt.Rows.Count; i++) {  
  10.                 Mobiles mob = new Mobiles();  
  11.                 mob.slno = Convert.ToInt32(dt.Rows[i]["slNo"]);  
  12.                 mob.MobileName = dt.Rows[i]["MobileName"].ToString();  
  13.                 mob.Price = Convert.ToDouble(dt.Rows[i]["Price"]);  
  14.                 mob.Url = dt.Rows[i]["Url"].ToString();  
  15.                 list.Add(mob);  
  16.             }  
  17.             return View(list);  
  18.         }  
Now, lets design the view to populate the data with the images. Our Index view is shown below.
  1. @model IEnumerable < DapperProject.Models.Mobiles > @ {  
  2.     ViewBag.Title = "Microsoft Mobiles";  
  3.     Layout = "~/Views/Shared/_HomepageLayout.cshtml";  
  4. } < link rel = "stylesheet"  
  5. href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" > < /script>   < script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script>   < div class = "row" > @foreach(var m in Model) { < div class = "col-md-4" > < div class = "row" > < h4 > < span id = "mobilename"  
  6.     style = "color:darkred" > @m.MobileName < /span></h  
  7.     4 > < p > < span class = "glyphicon glyphicon-heart"  
  8.     style = "color:red;pointer-events:fill"  
  9.     contextmenu = "Added To WishList" > < /span></p > < /div>   < p > < img src = "~/Images/@m.Url"  
  10.     style = "overflow: hidden; position: relative; width:200px; height:200px;" / > < /p>   < p > < a class = "btn btn-default"  
  11.     href = "" > View More» < /a><p><span class="glyphicon glyphicon-shopping-cart" style="color:green"></span > < /p>   < /p>   < /div>    
  12. } < /div>  
Now, just run the project and you will find all the data attached in the view with the images, as shown below.

Mvc

In our next part, we will work on Master Entry details of this project with Login, Register, Adding products to cart etc.

Hope, you will like this article. If you have any doubt, you can ask me and I will try to answer all your questions.