Real Life Example Of ASP.NET MVC 5

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 data from the database then we can get it.).

  • The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.

The following diagram represents how MVC pattern works internally.

MVC

  • Everytime first request comes into controller.

  • Controller decides which action to be executed and that action goes to 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:

  • Guys who are an expert cook, they works in kitchen.

    Guys (Manager) who take order from customer & write down that order on small paper with appropriate table number i.e one.

  • Now some customer comes into the restaurant, the guy who is going to take an order shows menu card of this restaurant to that customer.

  • Customer see this menu card. For example, customer see items such as 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.

    order
  • After taking order from customer, that guy (Manager) give this small purchi to a man who is sitting outside the kitchen. This man who is sitting outside the kitchen is acting like a Controller in MVC, means every order is handled by this controller.

    This man gives order to appropriate cook for making the order ready.

  • The cook will see the order & try to make the food ready. If he needs some extra items to make food like for Dosa he need to make 1 Chatani from coconuts then cook, visit the fridge & take this coconut & make chatani ready by adding water, sugar etc. In this scenario the cook is taking data from the database means cook is acting like Model in MVC.

    cook
  • After some time, the order of that customer is ready. Now the man sit outside the kitchen, calls the waiter & tell him to serve this order to the customer who ordered from table number one.

    order number

  • Now waiter adds some items to make better look & feel of food like he add some.

Now the order is ready to eat. This is actual View in MVC. Waiter is responsible for making decorate view.
Ready to eat

Some steps to create MVC 5 Project

Step 1: 
Create one project in Visual Studio 2013.

project

Add one controller

Add controller

Step 2: Add one model to our project named MyOrder & add some properties:

  1. public int QtyPoha {  
  2.     get;  
  3.     set;  
  4. }  
  5. //public string Poha { get; set; }  
  6. public int QtyUpma {  
  7.     get;  
  8.     set;  
  9. }  
  10. //public string Upma { get; set; }  
  11. public int QtyDosa {  
  12.     get;  
  13.     set;  
  14. }  
  15. //public string Dosa { get; set; }
  16.   

  get order
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 user input like the following:

order
  1. @model MvcApplication1.Models.MyOrder@  
  2. {  
  3.     Layout = null;  
  4. }   
  5. < !DOCTYPE html >< html >< head >< meta name = "viewport"  
  6. content = "width=device-width" / >< title > GetCustomerOrder < /title>< /head>< body >< div > @using(Html.BeginForm("Test""Hotel", FormMethod.Post))  
  7. {@  
  8.     Html.Label("Enter Poha Qty")@ Html.EditorFor(m => m.QtyPoha, new  
  9.     {  
  10.         style = "width: 650px"  
  11.     }) < br / > @Html.Label("Enter Upma Qty")@ Html.EditorFor(m => m.QtyUpma, new  
  12.     {  
  13.         style = "width: 650px"  
  14.     }) < br / > @Html.Label("Enter Dosa Qty")@ Html.EditorFor(m => m.QtyDosa, new  
  15.     {  
  16.         style = "width: 650px"  
  17.     }) < br / >< input type = "submit"  
  18.     id = "submit" / >< br / > @ * @Html.Label("My Poha Qty : ") * @@ViewBag.QtyP  
  19. } < /div>< /body>< /html>  

Step 5: Now add action method to our controller as:

extra material
  1. [HttpPost]  
  2. public ActionResult Test(MyOrder m)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         int QtyPoha = m.QtyPoha;  
  7.         ViewBag.QtyP = QtyPoha;  
  8.         int QtyUpma = m.QtyUpma;  
  9.         ViewBag.QtyU = QtyUpma;  
  10.         if (m.QtyDosa != null)  
  11.         {  
  12.             return RedirectToAction("TakeExtraMaterial""TakeValuesFromDb");  
  13.         }  
  14.     }  
  15.     else if (m.QtyPoha > 0 && m.QtyUpma > 0)  
  16.     {  
  17.         return RedirectToAction("ViewForSnacs");  
  18.     }  
  19.     return View("GetCustomerOrder");  
  20. }  
  21. public ActionResult ViewForSnacs()  
  22. {  
  23.     return PartialView("ViewForSnacs");  
  24. }  

Step 6: Now for just understanding, how model can take data from database. I have created one sample database with table & added some dummy data into this table:


dummy data
  1. Create Table DataFromFridge(Potatos varchar(100), Onion varchar(100), CoconutCream varchar(100), ChatMasala varchar(100)) Insert Into DataFromFridge  
  2. values('50gram''20gram''5Spoon''5gram')  
  3. Select * from  
  4. DataFromFridge  

Step 7: Now create another controller for database connectivity. Firstly, add some namespace to get database connection:

controller
  1. using System.Configuration;  
  2. using System.Data.SqlClient;  
  3. using System.Data;  
  4. public class TakeValuesFromDbController: Controller  
  5. {  
  6.     public ActionResult TakeExtraMaterial()  
  7.     {  
  8.         int i;  
  9.         SqlConnection con = new SqlConnection();  
  10.         con.ConnectionString = "Data Source=Rupesh-PC\\SA;Initial Catalog=My_Hotel;Integrated Security=True";  
  11.         con.Open();  
  12.         SqlCommand cmd = new SqlCommand("select * from DataFromFridge", con);  
  13.         SqlDataAdapter da = new SqlDataAdapter(cmd);  
  14.         DataTable dt = new DataTable();  
  15.         da.Fill(dt);  
  16.         if (dt.Rows.Count > 0)  
  17.         {  
  18.             i = dt.Rows.Count;  
  19.         }  
  20.         else  
  21.         {  
  22.             i = 0;  
  23.         }  
  24.         ViewBag.DbValue = i;  
  25.         return PartialView("OrderIsReady", ViewBag.DbValue);  
  26.     }  
  27. }  

Step 8: Now add one folder to our project as Imgaes which will help us to show on UI part i.e. on partial views.

Add some images in this folder.

images

Step 9: Now create Partial View to show an output. Add image URL in this partial view:

  • Partial View for OrderIsReady & add the following code snippet:
    1. <img src="@Url.Content(" ~/Images/Dosa1.jpg ")" alt="IMAGES" height="600px" width="800" />  
    2. <br />  
    3. <br />  
    4. <p style="font-size:35px; color: blue">Db values contains: @ViewBag.DbValue </p>  
  • Partial View for ViewForSnacs & add some code like the following code snippet:
    1. <img src="@Url.Content(" ~/Images/Pohe.jpg ")" alt="IMAGES" height="300px" width="600" />  
    2. <br />  
    3. <br />  
    4. <br />  
    5. <img src="@Url.Content(" ~/Images/Upma.jpg ")" alt="IMAGES" height="300px" width="600" />  

Now our solution structure looks like the following:

Action Result

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.

Redirect

Step 11: Now our UI looks like the following. This is a Partial View.

partial view

Step 12: Now we will again rerun our application & enter only two values and check the controller. Now it will go to partial view of ViewForSnacs
& see our URL goes to Partial View of ViewForSnacs.

UI

For more understanding you can download the code.

Summary

This article will help fresher candidates to understand ASP.NET MVC 5 & real life example of MVC 5.

Hope you enjoyed this one. Post your suggestions in comments section.


Similar Articles