MVC4 Mobile Application Using View Model Architecture

Content

In this article I will describe how to build or create a small MVC4 mobile application with View Model Concept architecture.

Description

Apart from vs2012 if you need to develop any MVC4 application in vs 2010 you need to upgrade your vs 2010 to SP1 and after that you have to install the MVC4 application.

For a MVC4 application you will need the Chrome, Mozilla and I.E 9+ browsers. If you guys don't have a phone emulator installed in your system then you can just use the browser like a mobile emulator and can see your application. After all, MVC4 supports Adaptive rendering, in other words it is a responsive U.I.

Now let's begin our topic.

I am going to build a small application for patient feedback for a particular hospital.

In other words whenever a patient visits the hospital he can provide feedback online by selecting the Branch and Feedback type through their mobile devices.

So in our application there will be 2 dropdowns (Branch selection and Feedback type selections).

SO to fill in these dropdowns we will use the View Model Concept to avoid the viewbag and tempdata concept.

The Magic of ViewModel allows us to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view.

The following figure describes the concept of a ViewModel:

concept-of-a-ViewModel.jpg


The purpose of a ViewModel is for the view to have a single object to render. In other words the only responsibility, or concern, of the view is to render that single ViewModel object, aiding in a cleaner separation of concerns (SoC) in (SOLID) principle.

Putting the data manipulation code in its own location away from the view and controller, enforces SoC. Using View Models in MVC leads to more easily maintainable and testable code.

Step 1

Creating the DataSource

Create a separate folder named "CommonDataSource" under our application.

The first one is the "Branch" class and the code is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace FrstMVC4Application.CommonDataSource

{

    public class Branch

    {

        public static SelectList StateSelectList

        {

            get { return new SelectList(StateDictionary, "Value", "Key"); }

        }

 

        public static readonly IDictionary<string, string>

            StateDictionary = new Dictionary<string, string> {

      {"Choose...",""}

    , { "Alabama", "AL" }

    , { "Alaska", "AK" }

    , { "Arizona", "AZ" }

    , { "Arkansas", "AR" }

   

    };

    }

}

The "Branch" class is a simple Dictionary object containing two type parameters of type string. The class also contains the definitions for all the members in the Dictionary (i.e., the branches data).

The only property in the "Branch" class is the SelectList, which is an object that HTML Helpers use to render an HTML <select> element that displays a listing of grades. The type Dictionary<string, string> in the BranchSelectList property maps to the grades abbreviation then grade name, respectively.

Similarly we are creating the "FeedbackType.cs" class. See the following code:
 

using System.Collections.Generic;

using System.Web.Mvc;

 

namespace FrstMVC4Application.CommonDataSource

{

    public class FeedbackType

    {

        public static SelectList FeedbackSelectList

        {

            get { return new SelectList(FeedbackDictionary, "Value", "Key"); }

        }

        public static readonly IDictionary<string, int>

             FeedbackDictionary = new Dictionary<string, int>

    {

        { "Select the type ...", 0 },

        { "Leave a compliment", 1 },

        { "Leave a complaint", 2 },

        { "Leave some SPAM", 3 },

        { "Other", 9 }

    };

    }

}


Step 2

Creating the Model

Now we need a model that collects the Patient's name, the feedback message, Branch and Feedback type. We will create a PatientFeedback class as shown below.

Create a file PatientFeedback.cs under the Models folder and add the following code:
 

using System.ComponentModel.DataAnnotations;

 

namespace FrstMVC4Application.Models

{

    public class PatientFeedback

    {

        [Display(Name = "Patient Name is Required")]

        [Required()]

        public string PatientName { get; set; }

        [Display(Name = "FeedBAck Message is Required")]

        [Required()]

        public string Message { get; set; }

        public int FeedbackType { get; set; }

        public string Branch { get; set; }

      

    }

}


Step 3

Creating the ViewModel

Now the data is coming from various sources that need to be displayed in the view, coding and maintenance will be easier if we use a ViewModel.

View Models are a combination of one or more types that together shape data that goes to the view for consumption and rendering.

Actually a ViewModel is just a class.

Now we will create a separate folder named "Viewmodel" under our solution.

Under this folder we will create a viewmodel class named "PatientViewModel.cs".

Now see the following code under this class.
 

using FrstMVC4Application.Models;

using FrstMVC4Application.CommonDataSource;

 

namespace FrstMVC4Application.ViewModel

{

    public class PatientViewModel

    {

        public  PatientFeedback Patient{ get; set; }

        public Branch branch { get; set; }

        public FeedbackType FeedbackType { get; set; }

        public PatientViewModel(PatientFeedback patient)

        {

            Patient = patient;

            branch = new Branch();

            FeedbackType = new FeedbackType();

        }

        public PatientViewModel()

        {

             Patient=new PatientFeedback ();

            branch = new Branch();

            FeedbackType = new FeedbackType();

        }

    }

}


See in this class we have the reference of our model class and our commondatasources class.

We are passing our model class PatientFeedback object into the viewmodel constructor.

Step 4

Creating the Controller

Now it's the time for creating the controller class.

We will create a "PatientController.cs" class under the controller class.

Now see the following code:
 

using System.Web.Mvc;

using FrstMVC4Application.Models ;

using FrstMVC4Application.ViewModel;

 

namespace FrstMVC4Application.Controllers

{

    public class PatientController : Controller

    {

        [AllowAnonymous]

        [HttpPost]

        public ActionResult PatientInfo(PatientFeedback model)

        {

            if (ModelState.IsValid)

            {

                model.PatientName = model.PatientName;

            }

 

            return View(model);

        }

   [AllowAnonymous]

        [HttpPost]

        public ActionResult PatientInfo(PatientFeedback model)

        {

            if (ModelState.IsValid)

            {

                model.PatientName = model.PatientName;

            }

 

            return View(model);

        }

 

    }

 

    }

 

See in the controller class we are passing the PatientFeedback object into our action result "patientinfo".

At present we are only binding the dropdown. In my next article I will save this information in the database using the Entity Framework.

Step 5

Creating the View

Now we will create a view name "PatientInfo.cshtml" under the "Patient" folder under the main "View" folder.

Now we do the following code in this view for data manipulation:
 

@model FrstMVC4Application.ViewModel.PatientViewModel

 

@{

    ViewBag.Title = "PatientInfo";

}

 

<h2>PatientFeedBack</h2>

@using (Html.BeginForm("Results","Home"))

{

    @Html.ValidationSummary(true)

    <fieldset>

        <legend>Enter Patient Name</legend>

        <div class="editor-label">

            @Html.LabelFor(model => model.Patient.PatientName)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(Model => Model.Patient.PatientName)

           @Html.ValidationMessageFor(Model => Model.Patient.PatientName)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Patient.Message)

        </div>

        <div class="editor-field">

            @Html.TextAreaFor(model => model.Patient.Message)

              @Html.ValidationMessageFor(model => model.Patient.Message)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Patient.Branch)

        </div>

        <div class="editor-field">

            @Html.DropDownListFor(Model => Model.Patient.Branch, FrstMVC4Application.CommonDataSource.Branch.StateSelectList)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Patient.FeedbackType)

        </div>

        <div class="editor-field">

            @Html.DropDownListFor(Model => Model.Patient.FeedbackType, FrstMVC4Application.CommonDataSource.FeedbackType.FeedbackSelectList)

        </div>

        <p>

            <input type="submit" value="Save" />

        </p>

    </fieldset>

}

 

Step 6

Changing the routing

Now I will change the routing mechanism into the "RouteConfig.cs" file for directly opening our "patientinfo site".

Please see the following code:
 

routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Patient", action = "PatientInfo", id = UrlParameter.Optional }

            );


Now run the application; it will look like the following:

output-ViewModel.jpg

I have seized the browser and made it like the mobile emulator.

Conclusion

So in this article we get to learn the concept of viewmodel in MVC4 applications, especially in mobile applications where the UI contains a dropdown.
 

Up Next
    Ebook Download
    View all
    Learn
    View all