Tag Archives: MVC tutorial

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.

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.

 

It is the Best of Times and it is the Worst of Times for Programmers

screen shot 2013-03-05 at 1.07.11 pm

Across the past six years, the US economy was mired in a recession. Yet throughout it all, there was one bright spot: the IT and programming job market. It seemed as if no matter how bad things got in the economy as a whole, there was always demand for IT skills due to a lack of supply.

And while the IT job market remains strong, it continually puts workers in a good news/bad news situation. The good news, of course, is that there are plentiful jobs, especially when compared to other segments of the economy. The bad news is that the competition is so fierce, the path of change so great, that workers can’t be complacent.

If their skills decay or if they remain idle for even six months, there will inevitably be other programmers – both in the US and abroad – who’d be happy to fill the void. The bottom line? Don’t be complacent. Continue to grow and learn. Expand your skills by taking a Java tutorial video, MVC tutorial, or a jQuery tutorial!

Thousands of developers worldwide use LearnNowOnline to gain the technical skills they need to succeed on the job and advance their career.

ASP.NET Web APIs: Alternative Routing Conventions

aspnet tutorial1

 

Like ASP.NET MVC framework routing, you can change the default route mappings to a different pattern. This is rarely necessary, however. What is more common is the need to change the default way the Web API identifies a controller action, and Web API routing gives you several options to do this.

HTTP Method Attributes

You can explicitly bind HTTP methods to actions in the controller. This is handy if you feel the default naming conventions force you to write action methods that aren’t very self-descriptive. For instance, having a controller method named “Put” doesn’t explicitly tell you what it’s doing. Even a name like “PutBook” doesn’t really imply that a Book is being edited. Perhaps you’d rather use a name like “EditBook” or “UpdateBook.” All you have to do is explicitly bind the PUT method to that action by using an HttpMethod attribute.

This forces the routing to use the EditBook method for a PUT request that comes in for that controller.

AcceptVerbs Attribute

The AcceptVerbs attribute is used similarly to the HTTP method attributes. It is useful when you want to specify a list of methods tied to the action and/or HTTP methods besides the usual four (GET, POST, PUT, DELETE).

Action Names in the URL

Much like the ASP.NET MVC framework, you can set up Web API routing to look for an action name in the URL and use that action to process the request. This is not generally recommended as it is a step away from a truly RESTful service. You want URLs to describe a resource, not an action to perform on the resource.

However, if your routing becomes unduly complicated or you want to keep to the same patterns your developers are used to from ASP.NET MVC, you can set up a routing table to look for action names in the URL. First change the routing table in Global.asax to the following:

Then use the HTTP method attributes on your actions:

This action would fire in response to a URL such as:


ldn-pledgerwoodThis post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

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

ASP.NET Web API’s: Default Mapping

Web API Routing

If you have used the MVC pattern in your web applications, you are already familiar with the concept of URL routing. The ASP.NET MVC framework, for instance, knows which controller action to call by looking at pieces of the URL and using those pieces to identify the controller and the controller action.

Web API routing works in a similar way, except that the action is not specified in the URL. Instead, the action is selected based on the HTTP method used in the request.

Default Mapping

Like the ASP.NET MVC framework, you can find the default routing table for the Web API in Global.asax.

Contrast this with the default routing table for ASP.NET MVC controllers:

The differences in the properties that are set and the URL mapping pattern may seem subtle, but they are important. Not only do the two mapping schemes they also capture the primary differences between a RESTful API and something that maps to method names in a URL.

The first difference is the MapHttpRoute method. This method is used to map API routes as opposed to the MapRoute method, which is used for ASP.NET MVC routing tables.

The second difference is that “api” is a hard-coded value in the Web API map for URLs. This prevents mapping conflicts with the ASP.NET MVC framework. It’s quite possible for both your MVC controllers and your Web API controllers to have the same names, so having “api” as part of all Web API URLs makes sure your routing table uses the right controller for a request.

The third difference is that the routeTemplate does not have an action parameter like the ASP.NET MVC framework routes do. In ASP.NET MVC, the URL specifies the action that should be called. In the Web API, the API decides which action should be called based on the HTTP method handled bythe controller.

In order to map a request to a controller action, Web API routing goes through the following steps:

  1. Checks for an “api” in the beginning. If there isn’t one, it is handled by MVC routing, instead.
  2. Adds the word “Controller” to the value found in the {controller} parameter of the URL and uses this to find the appropriate Web API controller
  3. Looks for an action with a name that begins with the HTTP method used in the request. For instance, if a GET method is used, Web API will look for an action name that starts with the word “Get,” a POST method willtrigger an action that starts with the word “Post,” and so on.
  4. Maps any additional parameters to action parameters.

Table 1 shows how the HTTP method and the URL pattern will map to actions by default. Once again, remember that the action name only has to begin with the HTTP method name; everything else is irrelevant and can be whatever you want.

HTTP Method URL Matching Action
GET api/books GetAllBooks()
GET api/books/2 GetBook(int id)
POST api/books PostNewBook()
PUT api/books/2 DeleteBook(int id)
DELETE api/books/2 DeleteBook(int id)

Table 1. Example HTTP requests mapping to controller actions.

This post is an excerpt from the online courseware for our ASP.NET Web API Basics course written by expert Philip Ledgerwood.

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