Tag Archives: MVC

What’s new in MVC 5.2

mvc

Microsoft’s very successful model-view-controller architecture, or MVC, has been their flagship framework for developing next generation Web applications—and Microsoft continues to improve it with version 5.2 released just over two months ago. If you’re still hanging on to MVC 4, you’re missing out on many new and exciting features, and Microsoft has made the path to upgrade easier than ever.

So what’s so exciting about MVC 5? Let me start by hitting you with some of the big improvements with this latest release. If you want even more information or want to see some demonstrations of these new features, please check out our MVC 5.2 courses with expert Eric Greene.

One ASP.NET

In MVC 5, Microsoft introduced a new project type called One ASP.NET. This project type has the goal of saving the Web developer’s time by reducing the clutter of many single-focused Web templates constantly growing within Visual Studio. One ASP.NET creates a more “a la carte” model for creating applications so the developer can start with core functionality, and then add more and more components as various features and functionality are required. This allows developers to combine ASP.NET Web Forms, MVC, Web API and other project templates into a single project and not be restricted to use only one of them.

Bootstrap

From the brilliant minds of the Twitter software engineers came a CSS and JavaScript framework that has quickly become one of the most popular tools for front-end development. Bootstrap provides user interface tools and controls that allow developers to build rich Internet applications that auto-respond to changing screen sizes and devices. It takes away the drudgery of constantly tinkering with the CSS and JavaScript code necessary to get your site to perform professionally for all of your users.

Microsoft now includes Bootstrap templates in MVC 5 so you can take advantage of all its features right out of the box. In fact, Bootstrap is now the default HTML/CSS/JavaScript framework bundled with ASP.NET MVC. Bootstrap is managed by NuGet which means it can be automatically upgraded as the technology advances. You can discover more about Bootstrap by taking a look at our Bootstrap 3.1 courses with expert Adam Barney.

ASP.NET Identity

Before ASP.NET MVC 5, Microsoft had promoted its Membership Provider to handle security, authentication, and roles for your Web applications. But with the ASP.NET Identity, they completely rebuilt their security solution to include a whole new range of features. It still contains all the core functionality for authentication and authorization, but it also extends to support new forms like two-factor authentication (2FA) and integrated authentication. With 2FA, you can require multiple forms of authentication like the Google Authenticator or SMS text messaging. Integrated authentication allows you to work with many existing third-party providers like Google, Facebook, and Twitter. It allows your users to access your site using credentials from these and other providers, freeing you from the responsibility of managing credentials, and not forcing your users to memorize yet another password.

New Filters

Authorization filters have been around for quite a while in ASP.NET and have been a staple for most developers who need to set up security for their Web applications. Authentication filters, on the other hand, are new to MVC 5. These new filters allow for programming logic to occur before the authorization filter, giving developers the ability to better identify and control users entering their site. For example, developers can now assign a new authentication principal (think of it like a role) to a user logging in prior to the authorization filter, giving them better control at the individual Action/Controller level. Think of the authorization filter as providing a more global security model, one that covers the site as a whole, while the authentication filter provides a more specific security model that can be applied at more localized level.

Another new filter enhancement is filter overrides. Filter overrides allow you to define filters that apply to most of your application, either at the global level or at the controller level, but then have the option to actually override or turn off those filters at the action level or controller level.

Upgrading from MVC 4

Microsoft has made upgrading easy and painless for the developer. In a nutshell, most applications will simply need to update their NuGet packages, plus make a couple of web.config changes, and they will be off and running. The NuGet services manage all the individual components or packages that your Web application utilizes, like Razor and Bootstrap, and make sure that they are all on the latest releases relative your version of MVC. Keep in mind that in addition to moving to MVC 5, there are minor releases coming out as well. At the time of this writing, there have been 5.1 and 5.2 releases, but by the time you read this there may be 5.3 available and beyond. Regardless, migrations at this level are equally straightforward in their upgrade process.

Keep in mind that in many cases the migration forward is a one-way proposition. With each upgrade, your application is exposed to more and more features and functionality, which means you can’t go back once you start using it. But hey, why would you go back, right?

Finally, it’s not just ASP.NET MVC that is gaining new features—ASP.NET Web API, Razor, SignalR, Entity Framework, NuGet and many others are also improving. LearnNowOnline can help you keep up with the latest releases so you can be the best Web developer you can be. Check out our complete course list.

 

About the Author


martyblogpic2-150x150Martin Schaeferle
 is the Vice President of Technology for LearnNowOnline. Martin joined the company in 1994 and started teaching IT professionals nationwide to develop applications using Visual Studio and Microsoft SQL Server. He has been a featured speaker at various conferences including Microsoft Tech-Ed, DevConnections and the Microsoft NCD Channel Summit. Today, he is responsible for all product and software development as well as managing the company’s IT infrastructure. Martin enjoys staying on the cutting edge of technology and guiding the company to produce the best learning content with the best user experience in the industry. In his spare time, Martin enjoys golf, fishing, and being with his wife and three teenage children.

Going “Greene” with MVC 5.2

recyclekeyboard

We’re going “Greene” in our latest course releases— but don’t worry about recycling code in the big green dumpster at the end of your driveway. By “Greene” I mean Eric Greene, our newest instructor.

Eric is an independent IT professional who loves learning new things, sharing what he learns, and helping clients to solve business problems. He holds numerous software certifications and has experience programming mobile, web-based, and desktop applications using a variety of commercial and open-source platforms. Now Eric has joined forces with LearnNowOnline to produce two new courses to help you understand what’s new in MVC 5.2.

MVC or Model View Controller is an architectural pattern used for interface design. Each part of MVC has a different function. The Model controls the functioning aspects of the user interface. The View is the information from the Model—for example data-related graphics or other types of Views. The Controller is input information from the user that is relayed to the Model and does affect the View.

MVC  5 allows you to build web applications more efficiently.  See what’s new in MVC 5.2 with these new courses featuring Eric Greene:

MVC 5.2: OneASP.NET, Upgrading and Bootstrap
In this course, you’ll see that One ASP.NET makes new ASP.NET MVC project creation easier and more efficient… thus cutting down on wasted time. You’ll learn how to upgrade MVC  4 applications to MVC  5, again recycling old code instead of writing all new stuff. Then you’ll see how to use Bootstrap, a collection of tools for creating web applications that makes design easier and faster.

MVC 5.2: Views, Attributes, Identity and Filters
In this course, you will learn about the new enhancements to MVC Views such as Enum Helpers and unobtrusive Ajax for the MaxLength and MinLength attributes.  Another cool new feature bundled with MVC  5 is Attribute Routing.  With several new attributes, you can easily configure routes directly on the controller and its actions. These new enhancements make coding faster and easier.  You will learn what ASP.NET Identity is and review the default ASP.NET Identity code created by Visual Studio in new MVC  5 projects.  Finally, you will see Authentication Filters and Filter Overrides in action.

Check out these new courses to see why MVC  5 makes building web applications faster and easier than ever. You’ll be going “Greene” in no time as you learn how to do more with less.

 

About the Author

BrianBlogpicBrian Ewoldt is the Project Manager for LearnNowOnline. Brian joined the team in 2008 after 13 years of working for the computer gaming industry as a producer/project manager. Brian is responsible for all production of courses published by LearnNowOnline. In his spare time, Brian enjoys being with his family, watching many forms of racing, racing online, and racing Go-Karts.

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.

Choosing the Right Action – Microsoft SQL Server 2012

The job of the action invoker to select the appropriate action method is more complicated than may appear on the surface. There could be multiple overloaded methods with the same name in a controller, they may be decorated with different attributes that make their selection appropriate in some scenarios and not others, their action method name may be different from their class method name, and other complications. Designing an effective controller requires that you understand how the selection process works.

The first thing that the action invoker does is to look for the action portion of the route definition for the request. Using the default route defined in a new MVC application shown below, it is the name at the second position.

 

Even if the current URL doesn’t include the action portion of the route, the default route definition defines it to be the “Index” action.

Once the action invoker has the name of the action, it needs to map that action name to a method of the controller. The simplest case occurs when there is a single method in the controller class with a name that matches the action name. For example, in a new MVC application the Index action of the Home controller maps to the single Index method in that controller.

But what qualifies as an action method? Is every method defined in the controller a potential action method? Not at all. There are a few requirements that a method must meet for the action invoker to consider it to be an action method candidate:

  •  It must be a public method and not marked as static.
  •  It cannot be a method defined on System.Object or the Controller base class. In other words, it must be defined within your custom controller object, not inherited from another object. So ToString could not be an action method because it is defined on System.Object.
  •  It cannot be a special method, such as a constructor, property accessor, or event accessor.
  •  It cannot have the NonActionAttribute decoration. This attribute is handy if you want to include a public method in a controller but don’t want to use it as an action method.

Taking all these restrictions into consideration, the action invoker uses reflection to find all methods in the controller with the same action name as the action name specified in the URL and meet the previous requirements.

But here is where things get a bit murky. Through the use of attributes on the controller’s methods, there could be multiple methods with the same name, the action name could be different from the method name, and there may be a selector attribute that restricts which requests an action method can respond to. This can create a bit of a gauntlet that the action invoker must navigate in order to find the correct action method, so let’s explore these action method features.

WARNING! By default, anyone anywhere could invoke any public method you create in a controller, unless you decorate the method with the NonAction attribute. This sounds scary, but most of the time the only public methods you have in a controller class will be action methods, so this is a non-issue.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely. 

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

The MVC Architecture

As the name implies, there are three primary components of an MVC framework: one or more models, views, and controllers. These components define the response cycle of a user interaction with an application.

  •  Model: A domain-specific set of classes that provide an interface into the data, implement domain-specific business rules, and reflect application state. The model may or may not wrap a persistent data store such as SQL Server or other database server. Usually the model will consist of a data access layer or some kind of object-relational tool such as LINQ to SQL, Entity Framework, or NHibernate.
  • View: The application’s user interface, which serves to render the model in a form that the user can interact with. An application will typically have multiple views associated with a single model, each used for different purposes. In a web application, the view is generally defined by HTML and contains no code or logic, other than what is necessary to display the view to the user and allow the user to interact with the view.
  • Controller: Receives requests from the user and initiates a response, interacting with the model as necessary. The controller also handles the overall application flow. In a web application, the controller usually responds to HTTP GET or POST inputs, hands the request over to the model that implements the business rules, and then selects the view subsequently displayed to the user.

The user’s interaction with a web-based MVC application generally follows this pattern:

  1. The user interacts with the web page in some way, such as making selections in a form and clicking a submit button.
  2. The controller handles the input and routes the request to the appropriate action, which is usually a public method of the controller class.
  3. The controller notifies the model of the user’s action, usually resulting in a change to the model’s state.
  4. The controller then selects a view, which queries the model in order to generate a new web page. In essence, the controller tells the view to generate itself, based on the current model state.
  5. The user interface (the web page) awaits a new interaction from the user, and the cycle begins again.

Figure below shows how the various MVC application components interact with each other to handle a user request and generate a response.
mvcarchitectimg1The anatomy of an MVC request and response.

If you’re familiar with ASP.NET Web Forms development, notice that there are no page events involved in responding to a user request. This makes for a much cleaner, simpler, and more maintainable architecture for applications.

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.

MVC, Ajax, and jQuery

Screen Shot 2012-10-18 at 11.46.55 AMMany people see Ajax as the technology that saved the web, that made it possible to create much richer Web 2.0 applications than was ever possible using just HTML and plain old JavaScript. Part of the key to Ajax’s success is that it uses standards-based, widely implemented technologies instead of proprietary tools like Flash, Air, Silverlight, and many others that have sprung up to overcome the perceived limitations of HTML. Ajax has the benefit of ubiquity: all modern browsers have an implementation of JavaScript and
include the key object used to make asynchronous calls to the server, XmlHttpRequest.

Ajax is a powerful web technology because it makes pages far more interactive to the user, performing actions and updating parts of the page without requiring a full page refresh and accompanying flash of a blank page. This is one of the biggest visual differences between a web application and a rich client application, and gives the illusion of running on the client machine even though it is in a browser. An “Ajaxified” page feels faster to the user and reduces the load on the server by requesting small chunks of data and HTML rather than the content of full pages on every user action. Ajax is inherently asynchronous, so it leaves the user interface responsive to the user even if the last operation takes a while to complete.

Ajax is not, however, a panacea. It is a bit past its prime as the buzzword du jour of the last decade, but it is still too easy to get carried away with it and use it as though it solves all web problems. Here are a few of the problems:

  • Ajax requires that JavaScript be enabled on the client browser, not something you can assume in this day and age of security threats.
  • Unless you plan carefully to hook your pages into the browser’s history, the user won’t be able to use the back button to return to a previous page state. This is something that can be a bit unsettling to a user, when the back button takes them to an entirely different page rather than an earlier state of the same page.
  • By default, users also won’t be able to bookmark a link to the one product out of your entire catalog that they want to buy for their kid’s next birthday. This is because the application has to build in support for supporting page state through the URL.
  • Sites that make heavy use of JavaScript may come with many hundreds of thousands of bytes of script files. Even with caching, that can slow things down dramatically.
  • It also doesn’t help that JavaScript is notoriously slow, although modern browsers are improving performance.

Nevertheless, a well-designed site can handle most of these problems, both through careful design and judicious use of Ajax and other client-side features. The vast improvement to the user experience on sites that use Ajax can easily be worth the potential negatives, particularly since careful design can largely negate the problems.

In the purest sense, it may seem like nonsense to talk about MVC and Ajax together, since they occupy entirely different worlds within a web application. MVC is a server-side technology: the browser rendering pages doesn’t have a clue about models, views, and controllers. All that the browser sees is HTML and whatever the view embeds in the page it sends to the browser. Likewise, Ajax is a client-side technology that makes clever and sophisticated use of JavaScript and HTML’s document object model (DOM) to make pages far more interactive than is possible with just HTML. Of course, Ajax makes calls to the server to receive data used to update the page in response to user actions, but most of the time that is a clean, well-defined interface, often using some kind of web service implemented on the server. On the face of it, it doesn’t seem like there should be much to cover in a joint MVC/Ajax chapter, right?

Well, no, not right (as you probably guessed, based on the fact that this chapter exists). It turns out that there are some nice synergies in using the two technologies together. This is because MVC includes features that make it easier to implement custom Ajax features in a web page and because Ajax on the client can interact with action methods on the server to more effectively respond to user requests. This chapter will introduce you to these two broad ways that MVC can work together: on the server, mostly through features you can include in view definitions, and on the client in the client-side JavaScript you can include in a page. One nice thing about using these technologies together is that you can avoid writing much, if any, JavaScript code if you want, or you can write as much as you want to really make your pages come alive for users!

James Curtis

This post is an excerpt from the online courseware for our MVC 4.0: Validation and Working with Ajax 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.

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.

HTML Helper Classes

HTML helpers are implemented in the System.Web.Mvc.HtmlHelper and HtmlHelper<T> classes. Views and partial views in MVC have an Html property that expose an HtmlHelper class, making it easy to use in a view. If you examine the interface of the HtmlHelper class in the documentation, you’ll find that it doesn’t implement most of the helper methods as native methods on the class. Instead, most of the helpers are extension methods implemented in the System.Web.Mvc.Html namespace, and HtmlHelper merely functions as
an anchor point for those helpers. Although HtmlHelper is most useful as the source of the helper extension methods, it has a number of its own native methods, of which Table 1 lists a few.

Method Description
AntiForgeryToken Adds a hidden form field with an anti-forgery token, used to
defend against cross-site request forgery (CSRF) attacks.
You can also extend this by passing in a salt value, domain
and path.
AttributeEncode HTML-encodes an attribute value.
EnableClientValidation Turns on client-side validation, causing the helpers to
generate the necessary client-side code.
Encode HTML-encodes a string or object value passed to the
method.
HttpMethodOverride Returns the value of a hidden field that identifies an override
method for the HTTP data-transfer method used by the
client.

Table 1. Some useful native methods of HtmlHelper.

The native HTML helpers included with HtmlHelper and its extension methods are useful, but cover only the most commonly used HTML elements. You’ll probably find yourself wanting more, and it is relatively easy to write your own helper methods, or even throw away the built-in helpers and use your own custom helper methods instead. Then, instead of referencing the System.Web.Mvc.Html namespace in your project, you replace it with your
namespace with your custom helper extension methods. This is just another way that you’re in control in MVC.

Types of HTML Helper Methods
MVC includes three broad classes of HTML helper methods: untyped helper methods, strongly-typed helper methods, and templated helpers. The untyped helper methods first appeared in the initial release of MVC, version 1, and generally take a string with the name of the property to which it is bound at runtime. The following code is an example of using a regular HTML helper to display a label, text box, and validation message to edit a Name property of the view model object, using the Label, TextBox, and ValidationMessage helper
methods.

A strongly-typed helper has “For” appended to the name of the method and takes a lambda expression that binds the helper to a model property at design time. This is in contrast to a regular helper that takes a string parameter. Strongly-typed helpers have the benefit of catching many kinds of problems at compile time instead of runtime, and IntelliSense fully supports them when you write code. The following code is an example of using strongly-typed helpers for the same Name property of the previous code, using the LabelFor,
TextBoxFor, EditorFor and ValidationMessageFor methods. Notice that each takes a lambda expression to bind the helper at design time.

@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.EditorFor(model => model.Notes) @Html.ValidationMessageFor(model => model.Notes)

Using a lambda expression lets you pass both the field that the helper is binding to and the value of the field. The strongly-typed helper method uses this information to intelligently determine how to display the data. It really is a rather elegant way to pass the information to the helper method.

TIP: Try misspelling a field name to see what happens. Specifically, misspell one
of the field names in one of the TextBox helper methods in the Edit view of
the AWLTProducts project, such as changing “Name” to “Nam.” You’ll find
that when you edit a product’s data you will receive a Compilation Error
since the Product model does not contain a definition for “Nam”.

Code that uses strongly-typed methods looks a bit more complex and requires more typing than the untyped versions, but only a little. And because the fields you are using are strongly typed, IntelliSense can help you where it couldn’t with just strings, as shown in Figure 12. Another benefit of using stronglytyped helper methods is that refactoring tools can update the views if you change field names.

figure12intellisenseFigure 12. IntelliSense provides a list of the properties of the Product object.

Templated helpers take the methods to an entirely different level, using built-in and custom templates to give you fine control over the HTML generated based on various templates. You can even throw an entire custom object at a templated helper, and the helper will use reflection to render all its properties—including nested properties—based on the templates defined for each data type, and reverting to a text box for any data types for which it has no template. The following code is an example of using a template helper to edit an entire view model, not just a single property of the object, using the EditorForModel method.

James Curtis

This post is an excerpt from the online courseware for our MVC4.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 4.0: The Role of the View

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.

The 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.

MVC4 Views
The Figure above. Anatomy of an MVC request and response.

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 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.