Introduction
In this article, we will discuss some basics & see a real life example of MVC 5.
Background
What is MVC?
MVC is an architecture pattern which separates logic, UI & database connection of our application. It’s divided into three broader sections, “Model
”, “View
” and “Controller
”.
- The “
View
” is responsible for look and feel of our application.
- “
Model
” represents the real world object and provides data to the “View
” (If we need from data from database, then we can get data from database).
- The “
Controller
” is responsible for taking the end user request and loading the appropriate “Model
” and “View
”.
The following diagram represents how MVC pattern works internally.
- Every time, first request comes into controller.
- Controller decides which action is to be executed and that action goes directly to View or through Model to View by taking data from database
Real Life Example of MVC 5
Suppose there is one restaurant, in this restaurant, some people are working as follows:
This man gives an order to the appropriate cook for getting the order ready.
- Guy who is an expert cooks work in the kitchen
- Guy (Manager) who takes order from customer & writes down that order on a small paper with appropriate table number, i.e., one.
- Now some customers come into this restaurant, the guy who is going to take an order shows a menu card of this restaurant to those customers.
- Customer sees this menu card. For example, customer sees items likes Poha, Upma, Dosa, etc. Now that customer would like to order Poha or dosa, then the customer can imagine how Poha or Dosa looks like.
- After taking order from
customer
, that guy (Manager
) give this small purchi to a man who is seating outside the kitchen. This man who is seated outside the kitchen acts like a Controller in MVC, means every order is handled by this controller.
- The cook sees the order & tries to make the food ready, if he needs some extra items to make food like for Dosa, he needs to make 1 Chatani from coconuts, then cook, visit to fridge & take the coconuts & make chatani ready by adding water, sugar, etc. In this scenario, the cook is taking data from database means cook is acting like Model in MVC.
- After some time, the order of that customer is ready. Now the man seated outside the kitchen calls the waiter & tells him to serve this order to that customer who has ordered from table number one.
- Now waiter adds some items to make better look & feel of food like he adds some...
Now customer order is ready to eat. This is the actual View in MVC. Waiter is responsible for making decorate view).
Using the Code
Some Steps to Create MVC 5 Project
Step 1
- Create one project in Visual Studio 2013.
- Add one controller.
Step 2
Add one model to our project named as MyOrder
& add some properties as:
public int QtyPoha { get; set; }
public int QtyUpma { get; set; }
public int QtyDosa { get; set; }
Step 3
Add one View to our project, by right clicking on action method.
Step 4
- Now add model to our view & add some input textbox for taking a user input as:
@model MvcApplication1.Models.MyOrder
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetCustomerOrder</title>
</head>
<body>
<div>
@using (Html.BeginForm("Test", "Hotel", FormMethod.Post))
{
@Html.Label("Enter Poha Qty")
@Html.EditorFor(m => m.QtyPoha, new { style = "width: 650px" })
<br />
@Html.Label("Enter Upma Qty")
@Html.EditorFor(m => m.QtyUpma, new { style = "width: 650px" })
<br />
@Html.Label("Enter Dosa Qty")
@Html.EditorFor(m => m.QtyDosa, new { style = "width: 650px" })
<br />
<input type="submit" id="submit" />
<br />
@*@Html.Label("My Poha Qty : ")*@
@ViewBag.QtyP
}
</div>
</body>
</html>
Step 5
- Now add action method to our controller as:
[HttpPost]
public ActionResult Test(MyOrder m)
{
if (ModelState.IsValid)
{
int QtyPoha = m.QtyPoha;
ViewBag.QtyP = QtyPoha;
int QtyUpma = m.QtyUpma;
ViewBag.QtyU = QtyUpma;
if (m.QtyDosa != null)
{
return RedirectToAction("TakeExtraMaterial", "TakeValuesFromDb");
}
}
else if(m.QtyPoha >0 && m.QtyUpma> 0)
{
return RedirectToAction("ViewForSnacs");
}
return View("GetCustomerOrder");
}
public ActionResult ViewForSnacs()
{
return PartialView("ViewForSnacs");
}
Step 6
- Now just for understanding how model can take data from database, I have created one sample database with table & added some dummy data into this table.
Create Table DataFromFridge
(
Potatos varchar(100),
Onion varchar(100),
CoconutCream varchar(100),
ChatMasala varchar(100)
)
Insert Into DataFromFridge values('50gram','20gram','5Spoon','5gram')
Step 7
Now create another controller for database connectivity. First, add some namespace to get database connection.
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
public class TakeValuesFromDbController : Controller
{
public ActionResult TakeExtraMaterial()
{
int i;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=Rupesh-PC\\SA;
Initial Catalog=My_Hotel;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("select * from DataFromFridge", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
i = dt.Rows.Count;
}
else
{
i = 0;
}
ViewBag.DbValue = i;
return PartialView("OrderIsReady",ViewBag.DbValue);
}
}
Step 8
Now add one folder to our project as Images which will help us to show on UI part, i.e., on partial views.
Add some images in this folder.
Step 9
Now create Partial View to show an output. Add image URL in this partial views.
- Partial View for
OrderIsReady
& add some code as:
<img src= "@Url.Content("~/Images/Dosa1.jpg")"
alt="IMAGES" height="600px" width="800"/>
<br />
<br />
<p style="font-size:35px; color: blue">Db values contains: @ViewBag.DbValue </p>
- Partial View for
ViewForSnacs
& add some code as:
<img src= "@Url.Content("~/Images/Pohe.jpg")"
alt="IMAGES" height="300px" width="600"/>
<br /><br /><br />
<img src= "@Url.Content("~/Images/Upma.jpg")" alt="IMAGES"
height="300px" width="600"/>
Step 10
Now run our application. I put some debugger here to understand how our application will work:
Now, we have entered all values, so it will redirect to TakeValuesFromDb
Controller.
Step 11
Now our UI looks like below. This is a Partial View.
Step 12
Now, we again rerun our application.
and enter only two values, then see in controller:
Now, it will go to partial View of ViewForScancs
.
Summary
This article will help beginners to understand ASP.NET MVC 5 & Real Life Example of MVC 5. Hope you enjoyed this one.