Archive for the ‘ASP.NET’ Category

May 11th, 2009

Creating Your First MVC ViewEngine

A question that I have been hearing a lot lately is:

How do I change the view location in MVC?

But what they really mean to say is:

How do I create a new ViewEngine that uses the view locations of my choosing?

It is actually very simple to do, and once you see it, I think you will agree with my assessment.  The first thing we are going to do to create our custom ViewEngine, is define the paths that we want to use for our master pages, view pages, and shared pages.  I have taken the liberty to define the following paths, you can customize them however you wish:

  • Master Pages:
    ~/Templates
    it use to be ~/Views/Shared or the controllers view
  • View Pages:
    ~/Views
  • Shared Pages:
    ~/Common
    it use to be ~/Views/Shared

The next thing we need to do is create a new class for our ViewEngine, for this example we are going to call it SimpleViewEngine.

public class SimpleViewEngine : VirtualPathProviderViewEngine
{
}

As you might have noticed from above our SimpleViewEngine inherits from VirtualPathProviderViewEngine, this is the root ViewEngine that uses the VirtualPathProvider (VPP). The VPP provides a way for web applications to read files off the file system in their local web application, so it is perfect for what we are doing. If you don’t want a file system based ViewEngine, and maybe want a ViewEngine based from the database, you can use the IViewEngine interface to create your own custom ViewEngine that fits your needs. (MVC is very flexible, by design)

The next thing we need to do is code our paths in to our SimpleViewEngine. We will do this in the constructor, so that they only have to be initialized once for the entire life span of our SimpleViewEngine.

public SimpleViewEngine ()
{
	/* {0} = view name or master page name
	 * {1} = controller name
	 */

	// create our master page location
	MasterLocationFormats = new[] {
		"~/Templates/{0}.master"
	};

	// create our views and common shared locations
	ViewLocationFormats = new[] {
		"~/Views/{1}/{0}.aspx",
		"~/Common/{0}.aspx",
	};

	// create our partial views and common shared locations
	PartialViewLocationFormats = new[] {
		"~/Views/{1}/{0}.ascx",
		"~/Common/{0}.ascx"
	};
}

As you can see the format is pretty straight forward. We create a string[] array with the paths of where our master pages, views, and common views are located. The only thing that we need to do is set place holders in our path so the the VirtualPathProviderViewEngine can replace the master name, view name, and controller name to construct our appropriate path.

  • {0}: is the view name or master page name.
  • {1}: is the controller name.

After we have done the hard part, which honestly wasn’t that hard, of creating the constructor with the paths, we just need to return the view objects from the constructed partial paths. Since we are using the standard ASP.NET Web Form (ASPX/ASCX) rendering engine. We are able to leverage the work already done by the MVC team and just return a new instance of the WebFormView object.

protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
	return new WebFormView(partialPath, null);
}

protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
	return new WebFormView(viewPath, masterPath);
}

Nothing really earth shattering here, just simply filling out the constructor with the proper parameters from our method, and then returning the newly created view. If you wanted to create a view based out of the database, or off your own syntax (meaning not ASP.NET syntax) then you would have to create your own view based off of the IView interface. But for this example we are only concerned with changing where our views are located.

There is one more thing that we need to do, and that is register our new SimpleViewEngine for use in the framework. The registration of view engines is done in the Global.asax, similar to the same way we register new routes.

public static void RegisterViewEngines(ViewEngineCollection viewEngines)
{
	viewEngines.Clear();
	viewEngines.Add(new SimpleViewEngine());
}

public static void RegisterRoutes(RouteCollection routes) { ... }

protected void Application_Start()
{
	RegisterRoutes(RouteTable.Routes);
	RegisterViewEngines(ViewEngines.Engines);
}

So we are now done. You have created a new view engines, defined your own routes, and registered this view engine with the MVC framework. Some other types of paths you may want to consider trying for your applications, using a custom ViewEngine, are special folders for your mobile or Facebook versions of your website.

  • Mobile: ~/Views/{1}/Mobile/{0}.aspx
  • Facebook: ~/Views/{1}/Facebook/{0}.aspx

I told you it was simple and straight forward, and I hope you agree that the MVC team has done an awesome job at providing a very flexible framework for us to tweak and customize it so it fits our applications.

Tags: , ,

Posted in ASP.NET, C#, How To | kick it on DotNetKicks.com | Bookmark | View blog reactions | 10 Comments »

April 16th, 2009

Recession Proof Your Programming Skills

In this economy you have to do everything to keep your skills fresh and current so that employers find you a desirable hire.  I really though the tips provided in 8 Ways to Recession-Proof Your Programming Career where spot on when this article came out last year.  And now that the TechRepublic has released 10 kills developers will need in the next 5 years.  I have decided to give you some of my favorite Wrox books that align very well to this TechRepublic article.

Learn C#

Learn ASP.NET

Learn ASP.NET MVC

Final Cover Photo

didn’t think I would leave my book out, did you? ;)

Learn Java

Learn PHP

Learn RIA & Web 2.0

I beleive all these books are a nessisty in helping you improve your career.  You don’t have to understand or know all of this technology, but you should at least have one of these books on your shelf.

Tags: ,

Posted in ASP.NET, C#, JavaScript, News, Personal, Programming, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

March 18th, 2009

ASP.NET MVC 1.0 Released

Final Cover PhotoIt was just announced at MIX09 that ASP.NET MVC 1.0 has been released for general use and is out of the Release Candidate phase.  There has been no word on the changes form RC 2 to this release version.  But I will keep this post updated as I learn more.  Also as of writing this the download hasn’t been posted to CodePlex either, but I am sure that it will be posted pretty soon.

I am assured by Wrox that the cover of the book will be updated to look like what is on the right of your screen.  So it should be any day now, so go pre-order a copy today by clicking on the cover image to your right and it will take you to the Amazon page where you can place your pre-order.  That way as soon as the book ships you will have a copy waiting on your front porch.

Update: It is available from Microsoft Download.  Probably on CodePlex by the end of the day.  Here is the final description of the download for your reading pleasure.

ASP.NET MVC 1.0 provides a new Model-View-Controller (MVC) framework on top of the existing ASP.NET 3.5 runtime. This means that developers can take advantage of the MVC design patterns to create their Web Applications which includes the ability to achieve and maintain a clear separation of concerns (the UI or view from the business and application logic and backend data), as well as facilitate test driven development (TDD). The ASP.NET MVC framework defines a specific pattern to the Web Application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can take advantage of the specific Visual Studio 2008 MVC templates within this release to create their Web applications, which includes the ability to select a specific Unit Test structure to accompany their Web Application development.

The MVC framework is fully extensible at all points, allowing developers to create sophisticated structures that meet their needs, including for example Dependency Injection (DI) techniques, new view rendering engines or specialized controllers.

As the ASP.NET MVC framework is built on ASP.NET 3.5, developers can take advantage of many existing ASP.NET 3.5 features, such as localization, authorization, Profile etc.

Update: Phil Haack just posted his MVC 1.0 Release Anouncement.

Tags:

Posted in ASP.NET, News | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 3rd, 2009

ASP.NET MVC 1.0 Release Candidate 2

Final Cover PhotoPhil Haack has announced the availability of ASP.NET MVC 1.0 Release Candidate 2.

You can download the new version from Microsoft. Source code and samples are also available on the ASP.NET CodePlex workspace.

Overall, this new version doesn’t have many changes in the area of development and tooling, but there has been improvement for deploying ASP.NET MVC applications.  The setup process now requires .NET 3.5 SP1 to be installed, where in the past it was optional because the additional assemblies where included with the install.

Don’t worry though /bin deployment is still supported, they are not taking a runtime dependency on SP1 other than our existing dependency on System.Web.Routing.dll and System.Web.Abstractions.dll. Thus you can still bin deploy your application to a hosting provider who has .NET 3.5 installed without SP1 by following these instructions.

They are also adding an option to the installer that enables installing on a server that does not have Visual Studio at all on the machine, which is useful for production servers and hosting providers.  To do a server install you just need to run the following command to install MVC on your server.

msiexec /i AspNetMvc-setup.msi /q /l*v .\mvc.log MVC_SERVER_INSTALL="YES"

Also because of the latest breaking changes from Beta to RC 1 & 2, we are taking the time between now and the final release of the MVC Framework to work on the book and make sure all the loose ends are tied up.

I also got noticed today that our final cover design is done.  So we are in the final stretch of this book.  The cover hasn’t been uploaded to Amazon yet, but if you are interested in pre-ordering a copy just click on the cover image to your right and it will take you to the Amazon page where you can place your order.

Tags: , ,

Posted in ASP.NET, News, Personal, Portfolio, Review, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

February 3rd, 2009

A potentially dangerous Request.Form value was detected in ASP.NET MVC

If you are getting something like the following error message in ASP.NET MVC:

A potentially dangerous Request.Form value was detected from the client (Description=”<p>some HTML text</p>”)

This is because of something called Request Validation, that is a feature put in place to protect your application cross site scripting attacks, as described in a White Paper on ASP.NET:

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

You need to add the following to your action method:

[ValidateInput(false)]
public ActionResult MyAction (int id, string content) {
    // ...
}

This is a new feature that was added to ASP.NET MVC RC1 and it will turn off request validation for this action and this action only. However you need to take special precautions to double check your content for script tags, which may indicate a cross site scripting attack. And if you find one make sure to do a simple replace that will render it harmless, such as:

content = content.Replace("<script", "[script").Replace("</script>","[/script]");

The above is not the most bullet proof code, but if you are using the ValidateInputAttribute on your action make sure to do a quick search on XSS or Cross Site Scripting and become familiar with the basics of this kind of attack.

Tags: ,

Posted in ASP.NET | kick it on DotNetKicks.com | Bookmark | View blog reactions | 9 Comments »

February 1st, 2009

Introducing the ASP.NET MVC (Part 7) - The Controller

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The Controller

In ASP.NET MVC, the controller contains the application logic for manipulating the model, handling user interactions, and choosing the view to display to the browser.  It can be thought of as the glue that holds the model and views together.

The controller, in actuality, is just a class object that inherits from the System.Web.Mvc.IController interface.  However, the typical implementation that you will encounter will be abstracted away from the IController interface, using an already implemented Controller class.  A properly implemented controller will contain one or more action methods, which we will cover in a later section of this chapter.

URL Routes

Another important part of the controller is the routes that define the URL.  The routes tell the controller factory which controller to instantiate and which action in the controller should be executed.  Let’s take the default route, which we learned about earlier in the chapter, as an example:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

In the above route definition, the URL can be constructed in the following manner:

{controller}/{action}/{id}

How the controller and routes work is one of those instances where it is easier to demonstrate the capabilities than to try to explain, so here is a table to demonstrate how the above route breaks up the following URL’s.

URL Controller Action ID
/ Home Index
/Home Home Index
/Home/About Home About
/Account Account Index
/Account/User/1 Account User 1

You may have noticed in the above table that some of the parts of the URL are not defined, and in the first case none of the parts are defined.  This is because there are a set of defaults defined for each part of the URL, and if the part of the URL is missing, then the default is used.  The default is defined with the following line in the above example code:

new { controller = "Home", action = "Index", id = "" }

In ASP.NET MVC there are two parts that need to be present in every route and they are controller and action.  This is because these two parts are required by the controller factory to find the correct controller object and then the correct action method in that controller.  All the other parts can optionally map to the action methods parameters.

When we talk about the controller factory from here on forward, we will be specifically referring to the ASP.NET MVC implementation, called DefaultControllerFactory, which is based on the controller objects using the following format: {controller_name}Controller (i.e. HomeController, AccountController).  There are many other types of controller factories, such as those based on the Inversion of Control principle, Castle Windsor, Sprint.NET, Structure Map, and Unity that are available from the MVC Contrib project located at www.codeplex.com/mvccontrib, if you are interested in learning more.

Controller Factory

The default controller factory in the ASP.NET MVC Framework, the DefaultControllerFactory, uses the following criteria, by default, when searching for available controllers for use:

  • The namespace of the web assembly with Controllers added on the end (that is, TheBeerHouse.Web.Controllers).
  • The objects in the namespace must be in the following format {controller_name}Controller (that is,  HomeController, AccountController).
  • The objects must also inherit from the IController interface.

These criteria can best be seen in the default solution that we saw earlier in this chapter. Let’s take another look at the controllers, as seen in Figure 2-25.

Figure 2-25

Figure 2-25

All of those criteria may have made the process of adding a new controller sound complex, but really all that you need to do to accomplish this is add a new code file to the Controllers directory and make sure the object in the code file inherits the Controller object from the System.Web.Mvc namespace.

Actions

The actions, like we talked about earlier in this chapter, are what binds the URL to the view being displayed.  They are not that difficult to understand, but to help separate out the different parts that make up an action I have divided them into a couple of logical sections below.  We are going to use the following code example to help bring all of the different sections together.

[AcceptVerbs(HttpVerbs.Post)]
[OutputCache(Duration = 600)]
public ActionResult GetCustomer (string name, string email)
{
    // code for executing the GetCustomer action
    return View(customer);
}

Methods

When we refer to an action, we are actually talking about a standard .NET method with parameters, return values, and attributes just like any other in your code.  The only thing that makes it an action is the fact that the method is inside of a controller class.

In the above example code the whole thing can be considered our method, and is probably pretty similar to every other method that you have ever seen or developed.

Results

A result is just another name for the return value of the method.  The only criterion for the return value is that it must be, or inherit from, the type ActionResult.

In the example code above, the result type is ActionResult, but it actually returns an object that inherits from ActionResult called ViewResult.  The ViewResult is created from a protected method available on the controller called View() which does all the necessary instantiating of the ViewResult to be returned.

Filters

The filters are implemented as attributes on the action methods.  There are two types of filters, one for actions and another for results.  The action filter refers to the action method and has two events. One is for custom processing before the action method has been executed and the other is for after the action method has been executed.  The results filter refers to the HTTP response and has the same two events that the action has, one for before the response is sent and one for after the response is sent to the browser.  We are not going to go into great detail about filters in this book, however we will be using them for such things as authorization, caching, and RESTful service results.

In the sample code above, the filter is the attribute called OutputCache.

Selectors

The selectors are implemented as attributes on the action methods.  Since both filters and selectors are implemented using attributes it is often difficult to determine the difference between them, but there is a huge difference.  The selectors are used when the controller factory is trying to determine which action method is the correct one to process the request, so they really have nothing to do with the action method execution, just the selection of the action method by the controller factory.

In the sample code above, the selector is the attribute called AcceptVerbs.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 5 Comments »

January 12th, 2009

Introducing the ASP.NET MVC (Part 6) - The View

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The View

In ASP.NET MVC, the view is the presentation of your applications’ business layer or model.  Typically with ASP.NET MVC this is HTML, but your view can be rendered in any form that can be transmitted over the internet, including JSON, XML, binary, RSS, ATOM, and your own customized protocol if you have one.

These dynamic ranges of views that, allow it to be capable of such a wide range of delivery types in the ASP.NET MVC Framework are because of a provider engine appropriately called the view engine.  The view engine is responsible for taking the controller and action names and then delivering the right view based on these names.

When I talk about the view engine from here on forward, I will be specifically referring to the ASP.NET MVC implementation, called WebFormViewEngine, which is based on the aspx, ascx, and master files.  There are many other types of view engines, such as Brail, NHaml, NVelocity, and XSLT that are available from the MVC Contrib project located at www.codeplex.com/mvccontrib, if you are interested in learning more.

ViewEngine

The default ViewEngine in the ASP.NET MVC Framework, the WebFormViewEngine, uses a hierarchy of folders and aspx and ascx files when rendering HTML pages to the browser.  The WebFormViewEngine, uses the standard ASP.NET Web Forms rendering engine that has been present in the framework since version 1.0, however the emphasis has been moved from control based rendering to an inline code based rendering that is reminiscent of its predecessor, plain old ASP.

Let’s take another look at the hierarchy that the default view engine uses, as seen in Figure 2-24.

Figure 2-24

Figure 2-24

The view engine treats aspx and ascx files almost equally, so that it is possible to render your HTML from an ascx or user control file, in the same way that an aspx or page file works.  As you can probably imagine there needs to be a hierarchy or order to which an aspx or ascx file is picked from the controller or Shared directory in Figure 2-24.  The default ASP.NET MVC view engine uses the following lookup order, from top to bottom, when trying to determine which view to render.

  1. ~/Views/{controller}/{action}.aspx
  2. ~/Views/{controller}/{action}.ascx
  3. ~/Views/Shared/{action}.aspx
  4. ~/Views/Shared/{action}.ascx

What this above lookup order means is that:

  • Controller directories are always checked before the Shared directory.
  • aspx or page files are always checked before the ascx or user control files.

The above lookup order even applies to master files, which allows you to select the master page template that you want to render with your view.  The lookup order that the master pages follows is slightly different than the page and user controls:

  1. ~/Views/{controller}/{master_name}.master
  2. ~/Views/Shared/{master_name}.master

Now that we have learned how view pages, controls, and master page are selected let’s take a little closer look at the files themselves.

ViewMasterPage, ViewPage, and ViewUserControl

In ASP.NET MVC there are three new takes on objects that you are probably familiar with from ASP.NET Web Forms.  These types probably come as no surprise, given what we just covered in the ViewEngine section and the title of this section, but they are as follows listed with their Web Form equivalent.

MVC Web Forms Description
ViewMasterPage MasterPage Responsible for providing a template to the page object.
ViewPage Page Responsible for the main content of the web page being viewed.
ViewUserControl UserControl This is used to sub-divide content and provide a modular

These object types in MVC are actually inherited from their Web Form counterparts, because they rely on their built in execution, in the ASP.NET Core, as a way of delivering the content through the servers such as IIS.  So all the interfaces you have become acustumed to (i.e. User, Context, Request, Response, IsPostBack, etc.) are still available in the MVC version of the page, user control, and master page.

However when developing for MVC there is a primary difference in the way in which an MVC view is constructed in the code-behind compared to its Web Form counterpart.  The best way to illustrate this difference is by showing you all that this required to have a fully functional view in MVC:

public partial class MyViewPage : ViewPage
{
}

Yup, that is all that is required, pretty cool huh?  This is possible because all the application logic that used to be in button clicks, post backs, and other event actions, has been moved to the controller actions.

It is actually considered bad practice in ASP.NET MVC to put any code in the code-behind file.

We have covered the basics of how views are rendered and found and the differences between MVC views compared to their Web Form counterparts.  We will be going in to a great depth of detail on programming views in later chapters of this book.  However we are not quite done, there are a couple more basics things I want to cover before moving on to The Controller section.  These include special properties designed to allow easy communication between the model, controller and view.

I have broken up the properties in to logical sections, so that we can discuss the purpose and intended use of each of them as envisioned by the ASP.NET MVC team.

ViewData, and Model

The ViewData property is used to store and transmit data from the model and controller to the view for rendering.  It can either be used as a Dictionary object, such as:

<%= ViewData["text"] %>

Or as a typed model object, such as:

<%= ViewData.Model.CustomerID %>

That is defined using generics in the inheriting object, such as a Customer type in the ViewPage:

public partial class EditCustomer : ViewPage<Customer>

It is a very versatile collection that is available to both the views and the controllers, and is passed via the ViewContext, which inherits from the ControllerContext.

TempData

The TempData property is a session-backed temporary storage dictionary, much like ViewData, which is available for the current request, plus one.  What this means is that any data you store in the TempData is kept in the session storage for one additional request, beyond the one you’re currently processing.

You may be scratching your head like I was when I first learned about TempData, and wondering why this would be important enough to include in the framework.  There is actually a very simple answer to this question, it allows you to pass data across requests, much like you have been accustomed to with the ViewState that is used in Web Forms.  It is also great for passing data between redirects, say you have the following scenario:

A user comes in to your site unauthenticated and you have to redirect them to the login page, but you what to display a message saying they need to login before viewing the content, but that message should display only when they don’t visit the login page directly.

Previously to accomplish this type of process you had to jump through hoops to determine if the user came from another page on your site, by checking the referrer or some other custom process that you had to come up with.  Additionally even after you got this done it was hard to customize that message to give the user some indication of where they came from or are going after they login.  TempData really comes to the rescue in this case, because you can the following is the only code that you need to display that message:

<% if (TempData["Message"] != null) { %>
<div class="message"><%= TempData["Message"] %></div>
<% } %>

You can even put this code in your master page so that you can display a message to your user on any page in your site, and all that you need is these three lines of code in the view.

HTML and AJAX Extension Methods

The HTML and AJAX extension methods provide a way to generate snippets of code for such things as form inputs and links.  For example if you wanted to generate a text box with the name attribute set to CustomerName, you just need to put the following in your view:

<%= Html.TextBox("CustomerName") %>

And it will generate the following HTML:

<input type="text" name="CustomerName" id="CustomerName" value="" />

As one added feature if you actually wanted to render the page with CustomerName already filled in, you would just need to set ViewData["CustomerName"], in the controller, equal to whatever you want to be rendered in the HTML.

An extension method for all of the form inputs available through HTML, have been provided with the ASP.NET MVC Framework, plus some other extensions such as AJAX implementations of the form inputs, and anchor link generation for controller actions.  Ninety-nine percent of all the HTML and AJAX extension methods that you will need to generate a web page have been provided in the framework, and if there is something that you must have, you can extend your own method from the HTML helper by doing the following:

public static string MyCustomControl (this HtmlHelper html, string name)

The this keyword is what is used to add these custom methods on to the HtmlHelper, which is represented as Html in the view pages, we will cover extension methods in greater detail later on in Chapter 6.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 11 Comments »

January 11th, 2009

Introducing the ASP.NET MVC (Part 5) - The Model

This is a continuation of my Introduction to ASP.NET MVC series. As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2. I am doing this so I can receive feedback on this chapter as early as possible. Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

The Model

In ASP.NET MVC, the model referrers to your applications’ business layer or domain objects.  These objects are responsible for persisting the state of your application, which is often, but note necessarily, stored in a database.

There really isn’t much to explain about the model as it relates to the ASP.NET MVC Framework, because it is based on your implementation and design of your business layer.  You can use any design pattern, methodology, and or custom process to accomplish the creation of the model:

  • DDD (Domain Driven Design)
  • TDD (Test Driven Design)
  • ALT.NET
  • Repository Pattern
  • Service Pattern
  • Specification Pattern
  • POCO (Plain Old CLR Object)
  • LINQ To SQL
  • ADO.NET Entity Framework
  • NHiberante
  • Data Tables
  • Your custom own business layer
  • Any combination of the above.

The point behind all of this is to try to demonstrate that it is up to you to define the model.  It is up to you to make the best decisions related to your requirements.  It is up to you to make it as simple or as complex as needed.  Everything is up to you, when we are talking about the M in MVC.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »

January 6th, 2009

Introducing the ASP.NET MVC (Part 4) - Your First ASP.NET MVC Project

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Your First ASP.NET MVC Project

To create your first ASP.NET MVC Project, you only need the prerequisites listed in the previous section.  To start, you first need to open Visual Web Developer 2008 or any version of Visual Studio 2008.

For the purpose of this section I will be using Visual Studio 2008 Team Development Edition.  I have, however, verified that this process works on Visual Web Developer 2008 SP1, Visual Studio 2008 Professional, and Visual Studio 2008 Team Development Edition.

After Visual Studio is open we need to create a new project (File > New > Project), see Figure 2-16 for an example.

Figure 2-16

Figure 2-16

Doing this will put you in the New Project screen, which you will then select your preferred language (in our case Visual C#).  From there we need to select Web @@> ASP.NET MVC Web Application, as depicted in Figure 2-17.

Figure 2-17

Figure 2-17

I am going to leave all the project configuration fields set to their default values as shown in Figure 2-17, you may configure them however you desire.  When you are done click OK, and you will see the screen shown in Figure 2-18.

Figure 2-18

Figure 2-18

You have probably not seen a screen like this before, even if you have done ASP.NET Web Forms development.  It is totally new to the ASP.NET MVC project creation process, and it automatically creates a unit testing project based on the default MVC project.

As an added feature it also allows you to select the testing framework that you would like to use, even non-Microsoft ones, such as NUnit, MbUnit, XUnit, Visual Studio Unit Test, and any others that decide to provide an interface to this Visual Studio process.

You can choose to create a unit project, or wait till a later time if desired.  For the purpose of this demonstration I am going to create a unit test project using MbUnit v3 from the drop down.  When you are done click OK, and you will see a Solution Explorer that looks like Figure 2-19.

Figure 2-19

Figure 2-19

This is what the default folder and file structure looks like for the ASP.NET MVC project, it has a separate folder for Models, Views (as seen in Figure 2-21), and Controllers (as seen in Figure 2-20).  As well as a set of default folders for storing JavaScript, CSS, or anything else you would want to deliver from your web application (as seen in Figure 2-22).

Figure 2-20

Figure 2-20

There are two controllers created by default.  The HomeController is used to render the home page and the about page.  The AccountController is used to authenticate a user with the standard ASP.NET membership provider.  These two controllers provide you everything you need to create a very basic web application.

Figure 2-21

Figure 2-21

For the views there is a mirroring of the controllers created.  One for Account and another for Home, in these folders there are aspx files that are call views.  Each of these views mirror an action method from the controller, by default.  As you will see later in this book there is a many to many relationship between the views and action methods.  In that an action method can map to multiple views and a view can have multiple action methods that use it.  Let’s not get to in-depth about the mapping of views and action methods at this point, because we will cover this in great detail later in this chapter and future chapters when implementing our application.

There is also a shared folder called Shared, which is, for lack of a better word, shared between all of the controllers and can be called by any of the controllers in the project.

The last thing I want to talk about before we move on to the rest of the files in the solution, is what appears to be a rouge Web.config file located under the Views directory.  This is a deliberate and strategic Web.config that is used, in addition to the one in the root, to block access to all the aspx files from getting accessed directly.  This Web.config file contains the following configuration information:

<?xml version="1.0"?>
<configuration>
	<system.web>
		<httpHandlers>
			<remove verb="*" path="*.aspx"/>
			<add path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler"/>
		</httpHandlers>
	</system.web>

	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<handlers>
			<remove name="PageHandlerFactory-ISAPI-2.0"/>
			<remove name="PageHandlerFactory-ISAPI-1.1"/>
			<remove name="PageHandlerFactory-Integrated"/>
			<add name="BlockViewHandler" path="*.aspx" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
		</handlers>
	</system.webServer>
</configuration>

It contains both configuration information for IIS 7, <system.webServer />, and IIS 6 and lower, <system.web />.  So you will be covered on which ever server you decide to deploy your MVC application to.

Figure 2-22

Figure 2-22

The rest of the solution files, includes JavaScript, Style Sheets, and other ASP.NET files that you should be familiar with.  The JavaScript files that are included by default are Microsoft AJAX and jQuery, as well as debug version of the files.

In the Fall of 2008, Microsoft announced a partnership with jQuery (www.jquery.com) to provide support and deliver jQuery with Visual Studio 2010 and some key projects.  One of the key projects that jQuery will be delivered with, is ASP.NET MVC.

If you are going to be using jQuery heavily in your application, as we are in this book, I highly recommend that you download the latest version of jQuery and the Visual Studio Intellisense Documentation for jQuery.  jQuery is constantly being developed and new features are getting added all the time, so it really pays to be running the latest version, so be sure to get the latest production and development files:

http://www.jquery.com

There are some standard ASP.NET files that we have all seen before, but I would like to take this opportunity to give you a quick overview of the purpose of the Global.asax and Default.aspx files.  These two files have a special purpose in an MVC application that you should be made aware of.

Global.asax

This is a standard ASP.NET file.  MVC takes advantage of the file to initialize all the URL routes, for mapping actions and controllers to URL’s, when the application is first started, using the Application_Start event handler.

public static void RegisterRoutes(RouteCollection routes)
{
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

	routes.MapRoute(
		"Default",
		"{controller}/{action}/{id}",
		new { controller = "Home", action = "Index", id = "" }
	);
}

protected void Application_Start()
{
	RegisterRoutes(RouteTable.Routes);
}

Default.aspx

This is a standard ASP.NET file.  It is not necessary on IIS 7, because of IIS 7’s integrated pipeline.  However you should not worry about it being present on and IIS 7 MVC application because, it will not interfere with the execution of the code.  The sole purpose, of this file, is to handle root requests on IIS 6 and lower, it does this using the Page_Load event handler of the page and forcing the request through the MvcHttpHandler, instead of rendering the page, which is empty.  The Page_Load event handler is shown in the code below.

public void Page_Load(object sender, System.EventArgs e)
{
	HttpContext.Current.RewritePath(Request.ApplicationPath);
	IHttpHandler httpHandler = new MvcHttpHandler();
	httpHandler.ProcessRequest(HttpContext.Current);
}

The final thing I want to cover is what the default ASP.NET MVC application design looks like when running in a browser, you can see an example of this in Figure 2-23.

Figure 2-23

Figure 2-23

It is a pretty basic layout, but it is a good example of the Home and Account controllers and can be used to render to and interact with the browser.

In the rest of this chapter, we are going to cover the basics of the ASP.NET MVC Framework, with a specific focus on the Model, View, and Controller.  So let’s get started.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »

January 5th, 2009

Introducing the ASP.NET MVC (Part 3) - Installing the Prerequisites

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Installing the Prerequisites

To start developing ASP.NET MVC and to run the code in this book, you will need the following prerequisites installed on your system:

  1. Visual Web Developer 2008 Express Edition SP1
    http://www.microsoft.com/express/download/
  2. SQL Server 2005 Express Edition
    http://www.microsoft.com/express/sql/download/
  3. Micorosft.NET Framework 3.5 SP1
    http://msdn.microsoft.com/en-us/netframework/
  4. Microsoft ASP.NET MVC
    http://www.asp.net/mvc/

You can cover prerequisites 1-3 by downloading just the Visual Web Developer 2008 Express Edition installation file, which includes .NET 3.5 SP1 by default and SQL Server 2008 Express Edition as an optional add-on during the install process.

If you have already installed all of the software above, or have an edition of the software that is better you may skip to the Your First ASP.NET MVC Project section.

Read the rest of this entry »

Tags: , , , , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 6 Comments »