first_page

ASP.NET MVC Notes

My progress with ASP.NET MVC is considered mentionable. My personal project is Songhay.Web.Mvc.ServerIndex—which is the index of my development server. This project helps to get a foothold on current Microsoft technologies within my scope—and it functions in the same manner as a SharePoint “My Site” (without SharePoint).

ASP.NET forms and MVC

You really, really can’t use ASP.NET forms (well) with ASP.NET MVC. The problem starts when you assume that ViewState will be properly maintained for, say, GridView paging. Some developers find the ListView helpful—others attempt to hack ViewState with the help of an online tool like KeyCreator.

The problem continues when you get used to using inline code blocks (<% %>) in views—and you realize (again) that ASP.NET server controls do not support code blocks very well.

“[ASP.NET MVC doesn’t work with ViewState and Postback?](http://stackoverflow.com/questions/366151/asp-net-mvc-doesnt-work-with-viewstate-and-postback)” “ASP.NET’s server-side controls work with WebForms, not MVC. MVC doesn’t use controls in the traditional ASP.NET sense (at least yet).”
“[Is ViewState relevant in ASP.NET MVC?](http://stackoverflow.com/questions/1170699/is-viewstate-relevant-in-asp-net-mvc)” “[It’s] present because `ViewPage` inherits from `Page`. However `Page` itself had no use for `ViewState` […it’s] used by `WebControls`. It is possible to include original `WebControls` in a View but doing so would be completely missing the point of separating control from view.”
“[ASP.NET MVC Validation of viewstate MAC failed error](http://www.dotneat.net/2008/12/13/ASPNETMVCValidationOfViewstateMACFailedError.aspx)” I do not recommend seeing the contents of this article as a solution because it opens a security hole in your application.
### MVC Model and View

The presence of the Model is made explicit when it is passed as a Generic Type argument when declaring inheritance for a ViewPage or ViewUserControl. Example:<%@ Import Namespace="Songhay.Web.Mvc.ServerIndex.Models" %> <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyViewData>" %> When a “view data” object is passed to a view, the Model object will now have the properties of this object. This means that you can use &lt;%=Model.MyViewDataProperty%&gt; instead of something like &lt;%#ViewData["MyViewDataProperty``"]%&gt;—or that old Eval syntax Scott Guthrie was showing (with strongly-typed View data) back in 2007. This ‘new’ (alternative) Model syntax is really cool and is the first time I have seen so explicit an expression of Model and View in an MVC framework! Here is a quote from Microsoft:

You can put views into one of two categories: those that use the ViewData dictionary and those that use strong typing. Views that use the ViewData dictionary derive from System.Web.Mvc.ViewPage. Our tag soup example uses this approach. Strongly typed view pages derive from System.Web.Mvc.ViewPage&lt;T&gt;, where T is a generic parameter to specify the type of the model. I recommend you use strong typing.

There is no longer a need to “register” ASCX files because of the Html.RenderPartial() helper. Jeffery Palermo insists that you can get rid of ASCX files entirely but I’m not seeing that being easy in my current version of Visual Studio 2008.

“[ASP.NET MVC and the templated partial view (death to ASCX)](http://jeffreypalermo.com/blog/asp-net-mvc-and-the-templated-partial-view-death-to-ascx/)” Simply, Jeff’s `/Views/Shared/ChartLayout.master` page would produce too many annoying syntax errors in my current build of Visual Studio 2008.
“[Guiding Principles For Your ASP.NET MVC Applications](http://msdn.microsoft.com/en-us/magazine/dd942822.aspx)” This Scott Allen article is very important. It should actually be printed for easy reference.
“[ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views](http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx)” “In addition to supporting a late-bound dictionary approach, the ASP.NET MVC Framework also enables you to pass strongly typed ViewData objects from your Controller to your View. There are a couple of benefits of using this strongly typed approach:”

“1. You avoid using strings to lookup objects, and get compile-time checking of both your Controller and View code”

“2. You avoid the need to explicitly cast values from the ViewData object dictionary when using strongly-typed languages like C#”

“3. You get automatic code intellisense against your ViewData object within both the markup and code-behind of your view page”

“4. You can use code refactoring tools to help automate changes across your app and unit-test code base”

“[ASP.NET MVC Tip #31—Passing Data to Master Pages and User Controls](http://stephenwalther.com/blog/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx)” “I’m not completely convinced by my own tip. I’m still tempted to use action filters to add view data for my master pages and user controls. The solution described In the last section, using abstract base classes, seems like a lot of work. I’m curious about how others have solved this problem.”
“[Typed View Data and Master Pages](http://iridescence.no/post/Typed-View-Data-and-Master-Pages.aspx)” “The ASP.NET MVC framework supports typed view data through the `ViewPage<T>` and `ViewMasterPage<T>` classes. Using these two classes together however, imposes a constraint caused by the generics involved; any `ViewMasterPage<T>` can only be used as the master page for pages that have the same type of view data. This means you cannot have a `ViewMasterPage<T1>` and then use that as the master for `ViewPage<T2>`, even if `T2` inherits from `T1`. …It’s the best solution I’ve come up with so far, but I’m not perfectly happy with it. If you have any better ideas, leave a comment!
### MVC Model Definitions and “View Data” Definitions

A key concept for me is containing the Model in two logical areas: Model Definitions and “View Data” Definitions. We should all know by now what Model Definitions are (the data-system-centric Model in MVC). What is new to me is the “View Data” definition—these define what will be sent as strongly typed data to the View. A previous post records how I divide the data layer conceptually: Procedures, Data Transfer Contracts, Input Definitions and Output Definitions—here, in ASP.NET MVC land, these “View Data” Definitions are my Output Definitions. With this single connection in place, I can see how MVC can get to the data—all the rest of the stuff falls into place (as of today). Now that I’ here, let me write these:

  • Input Definitions use Data Transfer Contracts to couple with Procedures for data input.
  • Output Definitions use Data Transfer Contracts to couple with Procedures for data output.
  • Data procedures are loosely coupled from input and output concerns because of Data Transfer Contracts.I’ve never written (or spoken) these lines before. So it’s time to get started!
“[Collection<T> versus List<T> what should you use on your interfaces?](http://stackoverflow.com/questions/271710/collectiont-versus-listt-what-should-you-use-on-your-interfaces)” “…by offering a simpler collection class or interface, you reduce the number of members that users of your API see, and make it easier for them to use.” This subject is important for ASP.NET MVC because a View will need to iterate over its strongly-typed “rows” of data. The recommended data type for these rows is `IC``ollection<T>`. By the way, `List<T>` implements `ICollection<T>`—so take advantage of interface-based polymorphism here!
“[What is the difference between ICollection and IDictionary in .NET/C#?](http://askville.amazon.com/difference-ICollection-IDictionary-NET-C%23/AnswerViewer.do?requestId=8375948)” “Finally, note that these are all interfaces, not classes. .NET gives you a few different types of collections, lists, and dictionaries to choose from, and the interfaces like `ICollection` and `IDictionary` give you a common way to access all of them without worrying about the details. When you create one in your own code, you’ll usually want to use the generic List or Dictionary classes.”
### MVC-Notes-Next

By no means do I “know everything” about ASP.NET MVC. The following table summarizes areas needing more investigation and study:

“[ASP.NET MVC Preview 5 and Form Posting Scenarios](http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx)” Posted a little over a year ago, Scott Guthrie writes about the importance of `[AcceptVerbs]` and `[ActionName]` attributes, “One way to work around these issues is to publish a single `"/Products/Create"` URL, and then have different server logic depending on whether it is a GET or POST request.”

Then he goes on to Model Binders, “Model Binders provide a way for complex types to be de-serialized from the incoming HTTP input, and passed to a Controller action method as arguments. They also provide support for handling input exceptions, and make it easier to redisplay forms when errors occur (without requiring the end-user to have to re-enter all their data again—more on this later in this blog post).”

Other topics of interest are: UpdateModel(), TryUpdateModel() and various issues around data validation.

“[VS 2008 Nested Master Page Support](http://weblogs.asp.net/scottgu/archive/2007/07/09/vs-2008-nested-master-page-support.aspx)” “One of the sites I recommend checking out is [http://www.opensourcetemplates.org/](http://www.opensourcetemplates.org/). This is an online repository of free HTML site templates that you can browse, download and use.”
“[ASP.NET MVC Tip #1—Create New HTML Helpers with Extension Methods](http://www.aspworkshops.com/blog/archive/2008/06/13/asp-net-mvc-tip-1-creating-new-html-helpers-with-extension-methods.aspx)” “You can add new functionality to the `HtmlHelper` class by creating new extension methods. An extension method looks just like a normal instance method. However, unlike a normal instance method, you add extension methods to a class by defining the methods in a completely different class.”

By looking at source code from big shots, I can see that this technique is encouraged for ControllerContext, HttpContext, HttpCookie and UrlHelper as well.

“[Authenticating Users with Windows Authentication (C#)](http://www.asp.net/LEARN/mvc/tutorial-18-cs.aspx)” “After you enable Windows authentication, you can use the `[Authorize]` attribute to control access to controllers or controller actions. This attribute can be applied to an entire MVC controller or a particular controller action.” With II7, by the way, enabling both Windows Authentication *and* ASP.NET Impersonation should yield expected results.
“[ASP.NET MVC Best Practices (Part 1)](http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx)” This Kazi Manzur aricle makes me miss a full-duplex laser printer! This is another one that deserves paper.

rasx()