ViewModels in ASP.Net MVC

The MVC architecture is all about separating the various layers of the applications in some logical parts. But this separation enforces some of the constraints on developers such as how to pass data from Controller to View. There are various ways to send those data to View such as using ViewData, ViewBag or TempData, the other ways is passing this data through ViewModels.

The view models group one or more entities or properties into one logical object which can be consumed by Views in order to render the contents on the View. The purpose of the View Models is to group all the necessary information required to render a view at a single place. This enforces a clear separation of Concerns, putting the data manipulation & domain entities away from the Controller & View. Using view models helps to create a good & maintainable code. Along with maintainable code, View Models are very beneficial in following cases

  1. Group all drop down related entities at a single place
  2. Master details records
  3. Pagination
  4. Dashboard details
  5. CRUD operations in which forms involves lot more controls

Although, from the above discussion it seems to be a more complex concept what View Model is, but actually it’s not. A view model is a simple C#/ VB.Net class, which contains some properties; those may involve primitive data type properties, or an entity or a set of entity.

Let’s create a ViewModel for following screen

The screen contains a text box for Name field & a drop down list for State. So ideally View Model should contain 2 properties 1 for Name & other for text box. So while rendering a view the ViewModel should be

This class will serve as a view Model when the view is rendered. So the controller will contain following code to render this form.

The above code will return a new form with State drop down list filled with 1 value NY. If we look at the AccountRegistrationGetViewModel carefully, you may notice [Required] attribute. This is one of the Data Annotations attribute supported by ASP.Net. They help us to validate the input data.

Now let’s create a view

It will generate a View which will contain following markup

But after validations user should be able to view the errors also we should accept these values at the Action Methods into a ViewModel. So let’s design that ViewModel.

So now when data is posted to the server in a Controller, we should catch this data in AccountRegistrationPostViewModel  . Also In order to show errors we need to add a property, as follows.

So our controller method will be So if validations are exploited these will be shown to user as below.

                 This is how we can use ViewModels. Initially it may look complex to create separate view Model for each function but later when it come to maintain the code, you will find it very very easy to fix the changes rather than striking you head on hardcoded strings.

You can find the source here.

Why not to use ViewData, ViewBag or TempData !

There are various ways of passing data from Controller to View or vice versa. For example when passing some values to View we can use ViewData Or TempData Or ViewBag. We set the appropriate values for keys in one of these & we can access it on view where ever we need it. This approach is used very extensively in some books as well as many of the blog posts. Though it is very easy & handy to set the values in ViewData, it has some pitfalls.

Before, we will see how we can pass the values from Controller to ViewData. Consider following simple example which contains a drop down list & a date time which we need to display on View. For that purpose controller would look something like this

[HandleError]

public class HomeController : Controller

{

private ICountryRepository _countryRepository { get; set; }

public HomeController(ICountryRepository CountryRepository)

{

_countryRepository = CountryRepository;

}

public ActionResult Index()

{

ViewData[“Country”] = _countryRepository.GetCountryList();

ViewData[“CurrentDate”] = DateTime.Now;

return View();

}

}

Here in Home controller we are setting the values for 2 entities one is Country & other is CurrentDate. Country is a drop down list whereas CurrentDate will display the current date time. The GetCountryList() function here returns IEnumerable.

The view for above will be like this

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Home Page

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

Country : <%: Html.DropDownList(“Country”, ViewData[“Country”] as SelectList) %>

Current DateTime : <%: ViewData[“CurrentDate”]%>

</asp:Content>

Though this looks pretty simple, however we are doing a lot of hardcoded string passing which is not at all good. The main pain with passing hardcoded strings is they can never be cause on compile time. Passing hardcoded string is not a big problem, we can solve it by using string Constants. But ideally, string hardcode should be avoided in order to avoid future mess which may occur during the maintenance phase of the project. Also we need to consider situations where we may need to show more than 10 items on the view, are we going to keep all these items to ViewData ? Also, see how we need to cast ViewData[“Country”]  to SelectList in order to pass it to the DropDownList helper function. While using ViewData all across the application, we need to take this pain.

Though this post was all about not using ViewData, ViewBag or TempData, there are situations where we need to use these as we cannot use View Models there. We will discuss these things in later posts.

Advantages of ASP.Net MVC

Since its release there is been constant debate among the Microsoft Community about Web Forms Vs ASP.Net MVC. Many people think eventually ASP.Net MVC will replace the traditional Web Forms. Basically ASP.Net MVC is another approach for Web Development with ASP.Net rather than a replacement to the traditional Web Forms. However, the fact is that both of them provide a different approach for web development. They are not here to replace each other, instead they will co-exist. While developing any project or applications you just need to make the right choice.

I will not jump into ASP.Net MVC Vs Web Forms. Instead, we will discuss about ASP.Net MVC advantages.

Following are some advantages of building applications using ASP.Net MVC.

  1. It makes it easier to manage the applications by dividing an application into Models, Views & Controllers.
  2. Support for Test Driven Development (TDD).
  3. It provides more control & extensibility over the page life cycle and provides the ability to substitute several key features of the framework. This was not at all available in ASP.Net Web Forms.
  4. It is an extremely extensible & pluggable framework where in the components can be customized or replaced as per need. This allows us to have better control over the framework.
  5. ASP.Net MVC uses REST (Representational State Transfer) based URL, which makes it SEO (Search Engine Friendly).
  6. There is no concept of ViewtState in ASP.Net MVC, which used to add a lot more JavaScript to the page making the final Html fat.
  7. Good support for existing ASP.Net MVC features. It lets us to use existing ASP.Net MVC features such as Forms and Windows Authentication, URL Routing, ASP.Net membership & roles, caching, session & state management, etc.
  8. Tight control over Html mark up. ASP.Net MVC provides a clean and standard compliant mark-up. Its build in helper methods generates standard output. It encourages you to create simple mark up with CSS.
  9. Open source. Unlike the other versions of ASP.Net, ASP.Net MVC is open source. This means you are free to download the original source code & compile it by customizing the source as per our needs.
  10. Since there are no Events, Post Backs & View States in ASP.Net MVC, it truly implements the stateless nature of the HTTP.

Introduction to ASP.Net MVC

This is my first post for ASP.Net MVC. As mentioned before we will be discussing only about ASP.Net MVC out here. The post only describes about the basics of ASP.Net MVC. Before reading this post, you don’t need to know much more about ASP.Net MVC, this post will certainly help you to know more about ASP.Net MVC.

Now there is a new boom in the Microsoft Technologies about ASP.Net MVC, since its launch it is continuously evolving through many phases of improvement. Currently there are following variant framework versions for ASP.Net MVC

  1. ASP.Net MVC CTP – Dec 2007
  2. ASP.Net MVC 1.0 – Mar 2009
  3. ASP.Net MVC 2.0 – Mar 2010
  4. ASP.Net MVC 3.0 – Jan 2011
  5. ASP.Net MVC 4.0 – Preview Available

As you can see from the above, at what pace ASP.Net is evolving. There are 3 stable versions still it launched in Mar 2009.

So, the question arise what is MVC in ASP.Net MVC?

The answer is MVC stands for Model-View-Controller. ASP.Net MVC is one of the Microsoft’s Web Application Development Framework just like ASP.Net MVC Web Forms are. ASP.Net MVC is architecture to develop ASP.Net Web Applications in a somewhat different manner than the traditional ASP.Net Web Forms development. ASP.Net MVC implements the well know MVC design patterns which is one of the most old & popular designing pattern across the developers for so many years.  Let’s describe what MVC stands for in ASP.Net MVC.

MVC bindings

  1. Models – A model is a C#/VB.Net class. This class may implement some data access logic, some business logic or just an representation of any business entity, such as Person, a customer, a book or even a database table also. This class can be accessed by Controllers & Views in order to pass data to & from the Controller or View.
  2. View – Views are the components that display the Applications User Interface (UI). A view is an ASPX or ASCX (User Control) which contains some HTML mark up. A view also can contain some inline C#/VB.Net code to develop dynamic pages. All page specific HTML is written in View, along with the formatting part. A request to view the View can only be made from Controller’s Action Methods.
  3. Controllers – A controller is again a C#/VB.Net class which always inherits Controller class in System.Web.MVC.Controller class. This class maintains the flow of the application’s logic. In other words we can say that Controller is the heart of the ASP.Net MVC applications. It acts as a mediator between Models & Views, creates a medium for communication between the two. Ideally it passes data from the Models to Views & Vice versa. Each controller contains some Action Methods which are responsible to render Views when browser requests for a View.

By default, MVC pattern allows us to create applications that separate different aspects of the applications such as Business Logic, Input Logic and User Interface. The UI logic belongs to the Views, input logic is managed by Controllers & the Business Logic is handled by Models. This clear separation allows us to manage the complexity when we build the applications.

In the next post we will discuss about advantages of ASP.Net MVC over the ASP.Net Web Forms.

Hello world!

After only thinking to start technical blog for last 2 years finally I will be starting to do some technical blogging.

The technical blogging I will do will involve, contents related to Microsoft Technologies such as ASP.Net, ASP.Net MVC, Entity Framework, LINQ, AJAX, Telerik ASP.Net MVC Controls, & other Microsoft Technologies.

So Happy reading to you & Happy blogging to me ……. 😉