Using the C# ViewModel to Create Great Views for Your Program

c sharp viewmodelMost applications are not very complicated. Most of the time, you can bind your user interface (UI) with your business logic, data storage, and processing code. However, large applications can get unwieldy in this design framework. You might have many components being developed by many programmers using many different tools. In this case you may want to split your UI development from your underlying processing code. The C# viewmodel handles this task for the .Net Framework.

The MVVM Programming Pattern

The C# ViewModel is a component of the Model/View/ViewModel (MVVM) programming architectural pattern. MVVM itself is not a programming framework or language. It is just a design philosophy you can use to develop your applications.

A variation on the Model/View/Controller (MVC) philosophy, MVVM is specially designed for UI development where a designer develops the user interface rather than a programmer. Designers are rarely programmers and are often better described as artists. As artists, most designers do not know how to program and tend to use word-processor-like programs to create their user interfaces. A viewmodel creates hooks for these word processors to link the UI with your programming code. This should improve the re-usability of your code and the collaboration between you and your UI designers.

MVVM separates your program development into three different layers.  Each layer represents a class serving a particular function.

  1. The view contains the UI and its logic.
  2. The viewmodel establishes how your data should be presented.
  3. The model processes your data and business logic. It also includes your databases.

Each class should only know about the component it directly interacts with. For instance the view only knows about the client and the view model whole the model only knows about the view model. In this pattern, the view model relays data and commands between the view and the model.

Learn about ASP.Net MVC programming at Udemy.com.

The ViewModel Class

The viewmodel sits between the model and view and serves as a buffer between them. It defines how you want to display your data and the functionality you need for your program to run properly. It only defines what you need to show the client. It does not actually implement anything or interact directly with the client. It is the view that displays the data and handles all user interaction. You use your viewmodel only to define the properties and commands the view uses to bind and manipulate this data.

The C# viewmodel coordinates how the view and model classes interact with each other. It relays commands and data between the two layers. Sometimes, you can just pass the data and commands along. Other times, you can use the viewmodel to perform some additional logic to either expose extra data to the view or to hide content from the model such as in input validations and visual feedback animation for long processes. For instance, your viewmodel can provide a Submit command for a form that the view can implement as a button of a link. Once clicked, the view runs this Select command which processes the form using commands from the model. This model could be a web service that does further processing or a data repository that just stores the data.

Learn how to create web services with C# on Udemy.com.

Working with a View Model

You create a ViewModel class by creating a class with only public members and public event handlers.  For instance, if you are creating a user registration page with three textboxes for the username, password, and password reentry box (for validation), you could implement all three as properties of your model like this:

public class Login

{

public String Username { get; set; }

public String Password { get; set; }

public String RePassword { get; set; }

}

However, you run the risk of overloading your database, especially if you need to hand that task off to someone else. A better idea would to implement these properties in a viewmodel like this:

public class Login

{

public String Username { get; set; }

public String Password { get; set; }

}

public class LoginViewModel

{

public String Username { get; set; }

public String Password { get; set; }

public String RePassword { get; set; }

}

Our view can take these public ViewModel properties to create login forms with strongly-typed benefits. To retrieve the data from the ViewModel, you implement an event handler with your ViewModel as its argument. The following example uses the HTTP Post event to process our login registration form.

[HttpPost]

public ActionResult Login(LoginViewModel viewModel)

{

//validate the ViewModel

//transforming Model (Domain Model) which is Login from ViewModel which is LoginViewModel

var login = new Login()

{

Username = viewModel.Username,

Password = viewModel.Password

};

//save the login var

return View();

}

As you can see, you retrieve the data from your C# ViewModel as you do with any other C# class and assign the values to your model’s own properties leaving out anything it shouldn’t have.

Learn how to create C# classes at Udemy.com.

Another use of C# ViewModel

You can use the MVVM pattern in any program. Let’s say, you wanted to list your latest posts latest comments, and post categories on your blog in a single view. Also, let’s say, you might change your blogging software soon and you do not want to have to write new code if you do. You can implement this list as a view model. You can have a BlogViewModel that contains your lists and bind your view to it. It will also contain the hooks you blog software expect to see in its plugins. In this scenario, your blog posts and comments serve as the model while your BlogViewModel servers as your ViewModel create for your particular view.

However, just because you can use a ViewModel in your program does not mean you should. Like any design pattern, MVVM and ViewModels have their advantages and disadvantages.  Even John Gossman, the creator of MVVM at Microsoft, noted that MVVM’s overhead is “overkill” for simple user interfaces. While the choice to use the pattern is largely preferential, you need to figure out if your project is large and complex enough benefit substantially from MVVM and C# ViewModels.