Prerequisites
- General knowledge of Web Applications.
- HTML, CSS, Bootstrap, JavaScript.
- 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 an ASP.NET project or MVC project, we must require the things, mentioned below.
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, and keep track of 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.
- Working with different layers in the project.
- Creating DAL logic.
- WorkFlow of the project.
- Creating different layouts for the different users.
- Working with the Home Page (showing data with the mobile images on the Home page)
Let's just start our project. Create a new MVC project, as shown below.
Now, choose ASP.NET Web Application.
Change the name of the project and add another class library and MobileDAL. Here, we have attached Solution Explorer, as shown below.
Now, let's start configuring the database with the project.
Go to the web. config and write the connection string, as shown below.
<connectionStrings>
<add name="Connect" connectionString="Data Source=*****; User Id=****; Password=****; Database=Demo" providerName="System.Data.SqlClient" />
</connectionStrings>
From here, let's see the project flow. Here is the complete project flow, which we have given below.
Here, the data will pass from View to the 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, the 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 operations from the database, as per our requirements.
Now, add a new class as "MobiledetailDAL.cs" in the MobileDAL layer and write the functions, mentioned below for establishing the connection with the database and perform DML and DDL operations.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace MobileDAL.cs
{
public class MobiledetailDAL
{
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
public static SqlConnection connect()
{
string connection = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
SqlConnection con = new SqlConnection(connection);
if (con.State == ConnectionState.Open)
{
con.Close();
}
else con.Open();
return con;
}
public bool DMLOpperation(string query)
{
cmd = new SqlCommand(query, MobiledetailDAL.connect());
int x = cmd.ExecuteNonQuery();
if (x == 1)
{
return true;
}
else
{
return false;
}
}
public DataTable SelactAll(string query)
{
da = new SqlDataAdapter(query, MobiledetailDAL.connect());
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Let's discuss each and every method, which is present in this class.
The first method is to read the connection string from the Web. config.
public static SqlConnection Connect()
{
string connection = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
SqlConnection con = new SqlConnection(connection);
if (con.State == ConnectionState.Open)
{
con.Close();
}
else
{
con.Open();
}
return con;
}
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".
Afterward, we pass this string to the 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.
public bool DMLOpperation(string query)
{
cmd = new SqlCommand(query, MobiledetailDAL.connect());
int x = cmd.ExecuteNonQuery();
if (x == 1)
{
return true;
}
else
{
return false;
}
}
As we have seen the architecture, we will pass the query from the controller, which will execute in the DAL Layer, this method is written to perform DML operations (CREAT, UPDATE, etc). So whatever query will be passed from the controller, 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.
For the first parameter, we will pass as the string received and for the second parameter, we have called the connection earlier, which we have made in the connect method.
Here, I am calling "MobiledetailDAL.connect()" for the connection string. Afterward, we are executing the command to do our work.
Whenever we will declare, it will work like this.
Now, the 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 a consistent look and feel on all the pages of our Application. It is the same as the master pages that we have in ASP.NET. We should always create a Layout in the shared folder.
To check how to create a 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 on 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.
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.
<script src="~/Scripts/vertical.js"></script>
<link href="~/Content/VerticalMenu.css" rel="stylesheet" />
<div class="row">
<!-- uncomment code for absolute positioning tweak see top comment in css -->
<!-- <div class="absolute-wrapper"> </div> -->
<!-- Menu -->
<div class="side-menu">
<nav class="navbar navbar-default" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<div class="brand-wrapper">
<!-- Hamburger -->
<button type="button" class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Brand -->
<div class="brand-name-wrapper">
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Search -->
<a data-toggle="collapse" href="#search" class="btn btn-default" id="search-trigger">
<span class="glyphicon glyphicon-search"></span>
</a>
<!-- Search body -->
<div id="search" class="panel-collapse collapse">
<div class="panel-body">
<form class="navbar-form" role="search">
<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>
</div>
</div>
</div>
</div>
<!-- Main Menu -->
<div class="side-menu-container">
<ul class="nav navbar-nav">
<li><a href="#"><span class="glyphicon glyphicon-user"></span>User Profile</a></li>
<li class="active"><a href="#"><span class="glyphicon glyphicon-home"></span>Home</a></li>
<li><a href="#"><span class="glyphicon glyphicon-envelope"></span> Message Center</a></li>
<li><a href="#"><span class="glyphicon glyphicon-phone"></span> Mobiles</a></li>
<!-- Dropdown -->
<li class="panel panel-default" id="dropdown">
<a data-toggle="collapse" href="#dropdown-lvl1">
<span class="glyphicon glyphicon-cog"></span> Setting <span class="caret"></span>
</a>
<!-- Dropdown level 1 -->
<div id="dropdown-lvl1" class="panel-collapse collapse">
<div class="panel-body">
<ul class="nav navbar-nav">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<!-- Dropdown level 2 -->
<li class="panel panel-default" id="dropdown">
<a data-toggle="collapse" href="#dropdown-lvl2">
<span class="glyphicon glyphicon-off"></span> Sub Level <span class="caret"></span>
</a>
<div id="dropdown-lvl2" class="panel-collapse collapse">
<div class="panel-body">
<ul class="nav navbar-nav">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>
</div>
</li>
</ul>
</div>
</div>
</li>
<li><a href="#"><span class="glyphicon glyphicon-signal"></span> Link</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
</div>
<div class="container-fluid">
<div class="side-body">@RenderBody()</div>
</div>
</div>
The renderBody method in the layout page helps to render the child page/view. It is just like the ContentPlaceHolder on the master page. A layout page can have only one RenderBody method.
To create a menu item, I have taken Bootstrap Glyphions.
Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis on 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
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.
Now, check the view. We will find the layout, which will be attached, as shown below.
@{
ViewBag.Title = "AboutUs";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>About</h2>
Now, run the Application.
As you see how we can create a layout page in MVC, so I can have multiple layout pages in my project (eg: For registered users, for anonymous users, etc).
Let's create one more layout page for the anonymous user. This is HTML code to create a simple layout, as shown below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">MoBBi99</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Login</a></li>
<li><a href="#">Register</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</nav>
<div class="container">
@RenderBody();
</div>
Let's use this page in the Index page, which is our Home page.
@{
Layout = "~/Views/Shared/_HomepageLayout.cshtml";
}
On 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.
USE [Demo]
GO
/****** Object: Table [dbo].[Mobiles] Script Date: 26-11-2016 22:01:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Mobiles](
[slNo] [int] IDENTITY(1, 1) NOT NULL,
NULL,
[Price] [money] NULL,
NULL,
[Description] [text] NULL,
CONSTRAINT [PK_Mobiles] PRIMARY KEY CLUSTERED (
[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]
GO
Now, let's add an Image folder to the Project and add some mobile images, as shown below.
Here is my data in the Demo table.
Let's create a model as a Mobile model, as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DapperProject.Models
{
public class Mobiles
{
public int slno { get; set; }
public string MobileName { get; set; }
public double Price { get; set; }
public string Url { get; set; }
public string Description { get; set; }
}
}
Now, we have the Home Controller with the Index method.
public class HomeController : Controller
{
MobiledetailDAL _mdal = new MobiledetailDAL();
DataTable dt;
public ActionResult Index()
{
string mycmd = "select * from Mobiles";
dt = _mdal.SelactAll(mycmd);
List<Mobiles> list = new List<Mobiles>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Mobiles mob = new Mobiles();
mob.slno = Convert.ToInt32(dt.Rows[i]["slNo"]);
mob.MobileName = dt.Rows[i]["MobileName"].ToString();
mob.Price = Convert.ToDouble(dt.Rows[i]["Price"]);
mob.Url = dt.Rows[i]["Url"].ToString();
list.Add(mob);
}
return View(list);
}
}
Now, let us design the view to populate the data with the images. Our Index view is shown below.
@model IEnumerable<DapperProject.Models.Mobiles>
@{
ViewBag.Title = "Microsoft Mobiles";
Layout = "~/Views/Shared/_HomepageLayout.cshtml";
}
<link rel="stylesheet" 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" style="color:darkred">@m.MobileName</span></h4>
<p><span class="glyphicon glyphicon-heart" style="color:red;pointer-events:fill" contextmenu="Added To WishList"></span></p>
</div>
<p><img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" /></p>
<p><a class="btn btn-default" href="">View More ยป</a></p>
<p><span class="glyphicon glyphicon-shopping-cart" style="color:green"></span></p>
</div>
}
</div>
Now, just run the project and you will find all the data attached in the view with the images, as shown below.
In our next part, we will work on the Master Entry details of this project with Login, Register, Adding products to the 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.