MVVM Pattern: Model-View-ViewModel in C# Programming

mvvm patternViewModels are customized classes that match business logic and your data model to provide a customized data model that you pass to your view. Model-View-Controller (MVC) patterns are the latest framework for the .NET C# language. MVC is used in other frameworks, but MVC C# is the latest in Microsoft .NET programming. If you work with IIS and Microsoft Web Forms, you will probably like MVC C#. You no longer need to keep track of page status and life cycles, and the Razor syntax makes visual presentation and back-end code more convenient.

New to MVC and C#? Create websites with the latest Microsoft technology using a comprehensive course at Udemy.com.

What is MVC?

Before you can get started with ViewModels, you need to know how MVC works. The ViewModel works with both views and models in MVC, so it’s a hybrid of both these components.

The Model-View-Controller framework separates each component of your web projects, which sounds difficult at first but it’s actually much easier to work with. If you’re coming from a Web Forms background, you might struggle with the concept at first, because Web Forms make you keep track of the page’s state such as loading, unloading, initialization and rendering. With MVC, all of these states are handled by the engine. You might wonder how you can work with pages that don’t allow you to control different states for controllers and page loading properties, but MVC takes care of it and lets you just worry about data and controls.

The “M” in MVC stands for model. The model represents your data. You can either send a model or a ViewModel to your front-end view. A model is typically a representation of a table in your database and data collected from that table. You can use LINQ, stored procedures or any other way to grab your data but it must fit with the model. In very simple terms, you could identify a model as a table in your database represented as a class in C#.

The “V” in MVC is the view. You can think of the view as the front-end web page that represents the controls, layout, colors images and interface for the user. What’s also new for front-end MVC web design is Razor. The Razor syntax is inline coding that you can use to display controls or data without using several lines of code. With Web Forms, you were forced to create functions and several lines of code to create a control and fill it with data. With Razor, you can use the model for data and render the control to the page with one line of code. You can also use Razor to add some logic functions in your view, but standards encourage you to include logic in the controller or ViewModel and keep only design elements in the front-end view.

Finally, the “C” in the MVC acronym stands for “controller.” The controller is where your logic and code are placed. The controller works with your models very closely to manipulate a ViewModel or model to send to your views.  The controller is where you’ll spend much of your coding time. You also instantiate ViewModel classes, fill them with data and send these ViewModels to your views from a controller. Think of the controller as the “middleman” between your front-end views for end-users and the database and data models.

Start from the beginning and learn as you go. Take a course at Udemy.com for MVC C#.

Getting Started with a ViewModel

A ViewModel is just a class. C# is an object-oriented language, so you’ll need to learn OOP to work with MVC C# frameworks.

A ViewModel is usually a hybrid between your business logic and your models. For instance, suppose you have a Customer model that represents a Customer table in your database. However, you have a view on your ecommerce website that contains some customer information with a list of recent orders. You could create a hybrid model named “CustomerOrderViewModel,” which is a class that contains the customer information and the order information you display in your MVC view.

Since a ViewModel is a class, you create a ViewModel the same way you create a class. In Visual Studio, you right-click your ViewModel folder, select “New” and then “Class.” Type a name for your class in the dialog box and click “OK.”

Visual Studio sets up a basic “shell” for your new class. Using the customer and order scenario, Visual Studio creates the following class for you:

using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace ViewModels

{

publicclassCustomerOrderViewModel

{

}

}

The first four lines are the necessary .NET libraries you need to work with MVC C# code. You will probably need to add to these libraries when you work with your project.

Next, the namespace is set. The namespace is automatically set to the folder where the class is located. When you have a different namespace than the rest of your code, you need to add this namespace to your code files. Therefore, with this ViewModel folder and namespace, you’ll need to add this namespace to the “using” section in your controllers to instantiate the class.

Finally, the class is defined with the “public” statement. The public keyword allows other classes to call this particular ViewModel.

To allow your other classes to instantiate this new ViewModel class, you need to define a constructor and also make it public. The following code adds this constructor to your ViewModel class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace WriterIdeas.ViewModels

{

publicclassCustomerOrderViewModel

{

public CustomerOrderViewModel()

{

}

}

}

The constructor can be overloaded as well to prompt users to send parameters to a secondary constructor. This example just has the basic constructor with no parameters required.

Since a ViewModel is a class, you can also create properties and methods in your ViewModel. These properties are what the view uses to display data, so they are an integral part of the class. To use a simple example, let’s add some real-world properties you would probably need in a CustomerOrderViewModel class. The following code adds two properties to your class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace WriterIdeas.ViewModels

{

publicclassCustomerOrderViewModel

{

 

publicstring userName;

publicint orderNum;

publicint userId;

 

public CustomerOrderViewModel()

{

}

}

}

This ViewModel has been given three properties: a username string, a orderNum integer and a userId integer. Remember that ViewModels are used to pass data to your views, so a customer page that lists the customer’s order would probably need these properties. You would probably have more properties, but for this example, we’re only using three.

Next, you probably need a method in your ViewModel. You could fill the ViewModel from your controller or you can fill properties with a method in the ViewModel itself. You might want to pass the ViewModel some data and then you use that data to fill its properties.

For instance, you might want to get a customer order and fill the ViewModel’s property with this information. You could use the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace WriterIdeas.ViewModels

{

publicclassCustomerOrderViewModel

{

 

publicstring userName;

publicint orderNum;

publicint userId;

 

public CustomerOrderViewModel()

{

}

 

publicvoid GetOrder(int orderId)

{

var orderInfo = (from o in db.Order where o.OrderId == orderId);

userName = orderInfo.username;

orderNum = orderInfo.ordernum;

userId = orderInfo.userid;

}

}

}

The GetOrder method is void, so it does not return any data. However, it does use a LINQ query to grab data from the Entity Framework object models and assign the data to the ViewModel’s properties. There are a number of errors that could generate from the above code, but this is why you use try-catch functions inside your method to ensure correct error trapping.

After you create your ViewModel code, you then need to use the ViewModel in your controller. The MVC C# .NET controller name is given the same name as your view, so match up the controller with the view and open it in your Visual Studio workspace.

Using the ViewModel in Your MVC Controller

You instantiate a ViewModel and send it to the view in the controller method called by the view. The default controller method used when you open a page is “Index().” The return type is “ActionResult” and the default View is returned. When you use the View function with no parameters, the default view is sent with no model or ViewModel.

The following is what the default view looks like for an Orders controller:

public ActionResult Index()

{

return View ();

}

There are a number of return functions you can use with the ActionResult return type. But, if you want to pass data to your view, you need a model or ViewModel.

The following code instantiates the ViewModel and passes it to the view:

public ActionResult Index()

{

CustomerOrderViewModel vm = new CustomerOrderViewModel();

vm.GetOrder(33);

return View ( vm );

}

Notice that there are two more lines of code in this controller’s Index method. Since this method is called by default, each time you access a page in your web application, this method is called and the view model is returned. Typically, you’d take some user input and then use that input to generate data in the view model. However, in this example, the static number 33 is sent to the “GetOrder” method.

First, the ViewModel is instantiated. You would not be able to do this if it wasn’t for the class constructor. If you have a constructor that requires parameters, then you would need to pass parameters with the instantiation. However, since this example does not require any parameters, you can instantiate the class with the above code.

Next, the ViewModel’s “GetOrder” method is called. Methods do any activity with your data, and they can be much more complex than this example. You might even need to call several methods to deal with the model’s data. In this example, the static number 33 is passed to the method. Usually, you pass dynamic data to the method, which is then used to generate a dynamic ViewModel. This method gets the information for order number 33.

Finally, the ViewModel’s data is filled with data and the model is returned to the view in the return function. You can actually instantiate a ViewModel and send it to the view without any data. The following code is an example of how to instantiate without sending any data:

public ActionResult Index()

{

return View (new CustomerOrderViewModel () );

}

You might wonder why you’d do such a thing. This is useful when you need to pass a model to the view, but you don’t have any data to pass by default. As a matter of fact, the above controller method is probably more real-world than the previous one.

Define a Model in Your View

Now that you’ve set up your ViewModel class and the controller, you must define the model’s use in the view. You define the use of your model at the very top (first line) of the view. The following code defines a model for the “Order” view:

@model project.ViewModel.CustomerOrderViewModel

The “project.ViewModel” is the namespace, but notice the ViewModel class name is defined with the “@model” directive. You can use any model with this directive, but you must make sure you define the right type. For instance, if you try to return an enumerated collection of values to the view with the above code, your application will throw an error.

To include a collection, you would use the following code:

@model ICollection<project.ViewModel.CustomerOrderViewModel>

Using the above code, you can then loop through each value and print it on the user’s web browser screen. You can also pass a “List” collection or an “IEnumerable” collection. The type of model you pass will determine how you can loop through your record set and model data.

If you want to learn more about ViewModels and C#, take a class at Udemy.com.