Tag Archives: MVC Views and Models

What is a Model? – MVC 4.0: Views and Models

The model in the model-view-controller pattern is the representation of the domain in an MVC application. The domain of an application is the problem area the application deals with, usually classes that represent business objects. For example, an online banking application might have a domain that consists of checking accounts, transfers, and bills. An application to manage a pet store’s inventory might have a domain that includes cats, dogs, and pet food. The model of your application consists of the classes that represent this domain.

To be consistent with the principle of separation of concerns, views and controllers should have no knowledge of the business rules in your domain or where the data for your domain is stored—if there is even a persistent storage for the data. Instead, views and controllers interact with the model and other application layers to handle those details.

Most real-world MVC applications will typically make use of some sort of data that is stored somewhere, usually in a relational database such as SQL Server or Oracle, or, at the very least, XML files stored on a server somewhere. No matter what the storage is, the application will contain some kind of data access layer to read and write data. Similarly, all non-trivial applications always have some kind of business rules, ranging from simple requirements that a customer’s last name be provided and that an email address must comply with Internet standards, to rules like all customers who did more than a million dollars’ worth of business with us last year get an automatic 20% discount on all purchases. These business rules may be handled in other layers of the application, but the rules that govern a specific object are present in the model.

Unlike a controller or view, in an ASP.NET MVC application a model is not defined by implementing a specific interface or inheriting from some framework class, or even because the class definition file is in the Models folder in Solution Explorer. Instead, one or more classes are models because of the role they play in the application.

This gives you enormous flexibility in how you implement a model. A model could be a simple class that represents data generated during a single session of the application, destroying the data when a user signs off. It could be a complex set of classes generated by Entity Framework to provide an objectrelational mapping to a relational database with hundreds of tables. Or just about anything in between. You’ll see variations of these options in this chapter. But at its core, a model is just a class that lets the controller interact with your domain and that provides data in that domain to a view.

TIP: A model is domain specific. This means that although you can implement a model just about any way you want, you generally will not want generic ADO.NET objects, such as DataSets, to serve as models. Instead, you’ll normally build a model for a specific application (or set of related applications) that serve specific data and business rule needs.

If a model you build is specific to a single application, you should create the model classes in the Models folder within Solution Explorer. This convention makes it simpler to work with the model classes and makes them easily discoverable when another developer comes along six months from now and tries to figure out what you did. But you can place a model class anywhere within an application. Remember that it is how a model is used that makes it a model, not where it is located or what it implements or inherits from.

If you use a model in several related applications, you can put one or more models in a class library and compile it into a standalone DLL, which you then reference from the applications that use the model.

A best practice in MVC applications is to maintain the separation of concerns between the components of the application. For models, this means that you’ll want to instantiate (or retrieve) the model in the controller’s action methods, using the methods and properties of the model to tell the model what actions to take relative to the data, and then send the data to a view for display to the user.

This chapter explores the use of models in an ASP.NET MVC application, how you can create them, and how you can implement validation rules. You’ll also explore how to interact with models from views and controllers, since none of these components exists in a vacuum. Models, views, and controllers interact in specific ways, so it is impossible to consider models without considering the other components as well.
ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Views and Models course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

The Role of the View – ASP.NET

The views in your ASP.NET MVC application are what a user sees. Views are the window into your application, and so is one of the most important parts of the application…along with all the rest of it!

Views provide one of the biggest reasons to use MVC instead of Web Forms. Unlike Web Forms, you have complete control over the HTML that the application generates. There are no server controls as there are in Web Forms that spew HTML, which you have little control over or that are hard to use with CSS and client-side JavaScript.

Having complete control over HTML sounds great in theory, but it could also mean that you’d have to write a lot more HTML by hand. One of the big selling points of Web Forms is that you can do drag and drop development, using server controls that generate massive amounts of HTML based on the properties you set and the data you bind to the controls.

But MVC has a lot of features built in that make the job of writing HTML and other code simpler and more manageable, while letting you retain control over most of the generated HTML. And when you need complete control, you can bypass the MVC features and write all the beautiful HTML you care to write.

The trick to writing good views in MVC is to keep the view focused on the user interface only. This means that there should be no code that directly reads or writes to a data store, no business rule implementations, nothing that isn’t directly related to interacting with the user. The ideal view should consist of a lot of HTML, maybe some client-side JavaScript (perhaps including Ajax), and a little code that reads data from the model or ViewData for the purpose of displaying data to the user. It might be appropriate to put some logic in a view, but it should only be presentation logic needed to dynamically interact with the
user. Anything else you should rip out and put in the controller or model. Make that your solemn goal.

The purest way to think about views is that the controller hands a model to the view, and the view converts it into something that is presented to the user. We’ve found this way of thinking to be a helpful context for understanding what views do and how to create them, as well as where to implement different kinds of logic.

In this chapter, you’ll learn about how views work, how you can add dynamic data to the view, how you can bundle and minify files, a little bit about the view engine that makes it all work, and ways to adhere to MVC’s DRY— Don’t Repeat Yourself—principle by creating reusable controls that you can use in multiple views.

Figure below shows a graphic view of the interactions of the components of an MVC application. In order to handle a user request, the controller interacts with the model in whatever way is necessary to respond to the request. The controller then selects a view and passes it whatever data the view requires to generate a page. The view engine then reads the view template and dynamically generates the HTML that is sent to the user.

theroleofview1

In this chapter, you’ll learn some of the many features you can use to build views that provide a robust user interface for your applications. The MVC framework has a rich infrastructure for creating responsive and attractive web sites for your users.
ldn-pledgerwoodThis post is an excerpt from the online courseware for our Introduction to ASP.NET MVC 4.0 course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.

Data Annotations

One of the many benefits of separating the concerns of the models, views, and controllers in an MVC application is that each of the three components is able to contain all of the code with which it is concerned. This means, for example, that the view is only concerned with the user interface, and contains only the code that displays a page and data to the user. It doesn’t have any business logic, data access, or any other code unrelated to the user interface.

In the same way, an MVC model is concerned only with data and business logic, nothing else. It interacts with a data store, such as SQL Server, and takes care of all the CRUD operations for maintaining data. In theory, this helps maintain a clean separation of concerns with the other MVC components.

But not everything is always so black and white or neatly partitioned. One issue that would seem like it crosses the component boundary is data validation. On one side, a relational database has certain requirements for data, such as a ProductID that is an integer, and that a company name is a string of one to fifty characters, no more and no less. It may also mandate that every product be assigned to a non-null product category, and that a U.S. Zip code be either five or nine characters in length.

Beyond those data type sort of requirements, you may also have business logic that requires that an email address be of a format that meets the requirements of the Internet, or that no customer can receive more than five orders a year with greater than a 20% discount. All of these data and business logic rules are in place to ensure that stored data is of the highest quality and that the application doesn’t allow any violations of the rules by which the business operates.

But where and how should you define these rules? On one hand, they are the domain of the model because most underlying data stores have requirements that must be met to store data. And because an MVC model is the proper location for business rules, it seems clear that they go in the model as well.

On the other hand, however, it is usually the user interface that needs to take a hand in enforcing the rules and helping the user provide the correct data by displaying error messages when she tries to save data that is missing a field. An input field of type text for the company name might have the max length attribute set to 50, to prevent the user from even entering too many characters in the first place. The user interface clearly has a role to play in data validation.

So where should you implement data validation, in the view or the model? The good news is that with an MVC model there is a clear answer: the model. You add attributes to the properties and classes that implement the model that define the data validation rules, and you can add other data annotations that guide how the view should use the properties of the model. The view can then look at those rules and annotations, and then enforce the rules and appropriately modify how it displays the data to the user. The view’s role in data validation is to take the rules defined in the model—without defining any of its own—and provide a user interface that enforces those rules.

Best of all, since the rules are part of the model, they’ll be in effect no matter where you use the model, across all views and controllers. There is no need to duplicate the rules anywhere in the application. This is an application of the DRY principle of an MVC application: Don’t Repeat Yourself.

James Curtis

This post is an excerpt from the online courseware for our MVC 4.0: Working with Data course written by expert James Curtis.

James Curtis  is a .NET Developer that primarily works in the UX space. He has worked on and for several large projects alongside Microsoft Consulting. James has spoken at several code camps about UX development for ASP.NET and SharePoint. He is an active participant in the development community tweeting and blogging about several topics in the UX area. James is an active consultant and is also assisting in several Start-ups contributing his UX experience.

MVC Project Template

ASP.NET MVC 4 is available in Visual Studio 2012 without any additional
installs. MVC 4 can easily be used in older versions of Visual Studio, but it
requires a separate installation. In Visual Studio 2012, there are two, basic
Project Templates: ASP.NET MVC 3 Web Application and ASP.NET MVC 4
Web Application. The MVC 3 template is included because of the relative
newness of MVC 4. The templates are available for both Visual Basic and C#;
other than la nguage, the templates are identical. You can access the templates

from the New Project dialog box that opens when you select File|New|Project

from the Visual Studio menu.

When you select the ASP.NET MVC 4 Web Application template, you have
the choice of several, specific project templates. The Internet Application

template creates a basic but fully functional MVC application, complete with a
model, a couple of controllers, and a few views. It uses best practice HTML
with a CSS (Cascading Style Sheet) file to format the views. It also includes
support for forms authentication and authorization, using the built-in features

of ASP.NET. (This is one of many ways that you can see how MVC is built on
top of ASP.NET, rather than being an alternative to it.) This template gives
you the option of creating a test project in addition to the main application
project, so that you can write unit tests.

The Intr anet Application template builds virtually the same project as the

Internet Application template, but uses Windows forms authentication. It also
gives you the option of creating a test project in the solution.

The Empty template sets up the project structure, including folders for models,
views, and controllers, and sets references to use the MVC framework, but no
default con trollers or models. It provides a great starting point for a new

application that you’ll develop from scratch, including building your own CSS
styles for views. If you want to create a unit test project with a project created
from this template, you’ll need to add that manually after you create the empty
web application.

The Basic template is very similar to the Empty template but includes common
Content an d Scripts that are useful to most MVC applications.

The Mobile Application template is almost exactly the same as the Internet
Application template except it incorporates jQuery.mobile to adjust the
application for delivery to mobile devices and does not use the built-in
authentication mechanisms for .NET applications.

The Web API Application is significantly different from the others in the sense
that it isn’t intended to produce a web site. Rather, it sets up a web services
application that runs according to RESTful URLs. The processing model is
very similar, but Web API Applications are used primarily to serve up data to
other applic ations. This template has no visual component to it.

With the exception of the Web API Application, it really doesn’t matter which
template you use. All provide support for MVC applications, and all are much
simpler than starting with a completely blank solution. In the following
sections, you’ll use the Internet Application template in order to explore the
structure of an MVC application.

ldn-pledgerwoodThis post is an excerpt from the online courseware for our MVC 4.0: Views and Models course written by expert Phil Ledgerwood.

Phil Ledgerwood has been a software developer for fifteen years. He currently works primarily in .NET technologies producing custom software for organizations of all sizes. He has also done extensive training for those same organizations in both technical and business process topics.