Click here to Skip to main content
15,886,362 members
Articles / Web Development / HTML

Real Life Example of MVC 5

Rate me:
Please Sign up or sign in to vote.
4.33/5 (4 votes)
5 Dec 2015CPOL4 min read 29.3K   3   14   3
In this article, we will discuss some Basics & Real Life Example of MVC 5.

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.

Image 1

  • 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:

Image 2

This man gives an order to the appropriate cook for getting the order ready.

  1. Guy who is an expert cooks work in the kitchen
  2. Guy (Manager) who takes order from customer & writes down that order on a small paper with appropriate table number, i.e., one.
  3. 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.

    Image 3

  4. 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.
  5. 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.
  6. 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.

    Image 4

  7. 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.
  8. 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).

    Image 5

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:

C#
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:
    HTML
    @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:
C#
[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.
SQL
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.

C#
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.

  1. Partial View for OrderIsReady & add some code as:
    HTML
    <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>
  2. Partial View for ViewForSnacs & add some code as:
    HTML
    <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:

Image 6

Image 7

Now, we have entered all values, so it will redirect to TakeValuesFromDb Controller.

Image 8

Step 11

Now our UI looks like below. This is a Partial View.

Image 9

Step 12

Now, we again rerun our application.

Image 10

and enter only two values, then see in controller:

Image 11

Now, it will go to partial View of ViewForScancs.

Image 12

Image 13

Summary

This article will help beginners to understand ASP.NET MVC 5 & Real Life Example of MVC 5. Hope you enjoyed this one.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I have 2.5+ years of experience as Software Developer as well as Professional Trainer on various technologies like C, C++, Data Structure, ASP.NET, ASP.NET MVC 5.0, C#, SQL Server 2012, Oracle 12C etc. I have conducted more than 50 hands on Seminars, Workshops for IT Industries, Colleges and training Institutes. I blog http://www.rupeshkahane.blogspot.in
Monthly Winner for contribution on C#Corner community for Nov 2015.

Comments and Discussions

 
Questiongood but it is not a reallife sample Pin
evrenp1-Sep-18 11:19
evrenp1-Sep-18 11:19 
Questionpurchi Pin
pikete10-May-18 3:24
pikete10-May-18 3:24 
PraiseGood one nice explanation Pin
Member 1106799410-Dec-15 18:01
Member 1106799410-Dec-15 18:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.