Widgetz SQL Server DB + ASP.NET MVC 3 Web Application Scaffolding

This is a quick walk through of how to setup a database, create some model objects, and build a scaffold for CRUD (Create, Read, Update, and Delete) all using ASP.NET MVC 3 and Visual Studio 2010.

Open Visual Studio 2010 and start a database project as shown.

SQL Server 2008 Database Project in Visual Studio 2010 (Click for full size image)
SQL Server 2008 Database Project in Visual Studio 2010 (Click for full size image)

Next create an ASP.NET MVC 3 Web Application in this solution.

ASP.NET MVC 3 Web Application (Click for full size image)
ASP.NET MVC 3 Web Application (Click for full size image)

Now open the Server Explorer in Visual Studio 2010 (You might have to click on View to find it if it isn’t already available in the main IDE). Right click on the Data Connections node in the Service Explorer Tree. Select Create Database and provide a name for the database.

Create a New SQL 2008 Database
Create a New SQL 2008 Database
New Database Dialog
New Database Dialog

Next in the Server Explorer, right click on the newly created database and select New Query. Then in the query window paste this SQL create script in and run it by right clicking and selecting execute.

[sourcecode languag=”sql”]
CREATE TABLE [dbo].[Widgetz] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Description] NTEXT NULL,
[Created] DATETIME NOT NULL,
[Terminated] DATETIME NULL,
[Addon] BIT NOT NULL,
[Active] BIT NOT NULL,
[Cost] MONEY NULL,
[ChildWidgetz] INT NULL
);

ALTER TABLE [dbo].[Widgetz]
ADD CONSTRAINT [PK_Widgetz] PRIMARY KEY CLUSTERED ([Name] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);

ALTER TABLE [dbo].[Widgetz]
ADD CONSTRAINT [DF_Widgetz_Created] DEFAULT (getdate()) FOR [Created];

ALTER TABLE [dbo].[Widgetz]
ADD CONSTRAINT [DF_Widgetz_Active] DEFAULT ((1)) FOR [Active];

ALTER TABLE [dbo].[Widgetz]
ADD CONSTRAINT [DF_Widgetz_Addon] DEFAULT ((0)) FOR [Addon];
[/sourcecode]

Once the table is created bring to focus the Solution Explorer and right click on the Database Project, selecting the Import Database Objects and Settings.

Import Database Objects and Settings...
Import Database Objects and Settings...

Next select the correct database connection, and leave everything else as it is set.

Selecting the appropriate database, options, and click next... (Click for the full size image)
Selecting the appropriate database, options, and click next... (Click for the full size image)

Next the wizard will finish importing the database objects.

Finished (Click for full size image)
Finished (Click for full size image)

If you look through the folder tree of the project you’ll find individual files for the table, defaults, and other object settings.

Now right click on the Models directory of the ASP.NET MVC 3 Project that was created earlier. Select add and then new item. In that dialog add a new ADO.NET Entity Data Model.

Yup, just when you think it had gone away...  ADO.NET (Click for full size image)
Yup, just when you think it had gone away... ADO.NET (Click for full size image)

A dialog will appear, select the option to Generate from database and click next.

Entity Data Model Wizard (Click for full size image)
Entity Data Model Wizard (Click for full size image)

Next select the correct database connection again, then click on Yes to save the sensitive data (which if you’re using windows authentication it isn’t really going to save anything dangerous). Make sure the entities are named appropriately and click Next.

Options for Creating the ADO.NET Entity Model
Options for Creating the ADO.NET Entity Model

The next screen, which may take a moment or two to display the list of tables and objects, will appear. Select the table that has been created and click on

Entity Data Model Wizard (Click for full size image)
Entity Data Model Wizard (Click for full size image)

Once done and finish is clicked, the entity model file will show the display view of the entity that was just created.

Entity Model
Entity Model

Now right click on the controller folder and select to create a new controller.

Add Controller (Click for full size image)
Add Controller (Click for full size image)

Be sure to click the advanced options and select the layout page.

Advanced Options (Click for full size image)
Advanced Options (Click for full size image)

Now click on Ok and then Add. Visual Studio 2010 will not generate the scaffolding for the controller and views around CRUD operations.

The Scaffolding in ASP.NET MVC 3
The Scaffolding in ASP.NET MVC 3

This might seem like an absurdly easy thing to do, and you’d be right. There are however many steps to turn this into a feasible, well design user interface, and provide a solid and intelligent user experience (UX) to the end user. Also, this is arguably a not so maintainable bit of work. If the end user ONLY wants to operate on the data with CRUD, then this is great. But the minute something else is needed a very different, testable, and maintainable architecture should be utilized instead of this generated scaffolding. Which in coming blog entries I will be covering some of the ways to create testable, maintainable, and better designed architecture around more than CRUD.  🙂

CODE: All the code for this project is available in the Lesson 1 – ScaffoldGeneratedWidgetz.

Windows Azure Table Storage Part 1

This is the first part of a two part series on building a basic working web app using ASP.NET MVC to create, update, delete, and access views of the data in a Windows Azure Table Storage Service.  The second part will be published this next Monday.  With that stated, let’s kick off with some technical specifics about Windows Azure Table Storage.

The Windows Azure Table service provides a structured storage in the form of tables.  The table storage you would setup within Windows Azure is globally unique.  Any number of tables can be created within a given account with the requirement that each table has a unique name.

The table storage account is specified within a unique URI such as:

http://myaccount.table.core.windows.net

Within each table the data is broken into collections called entities.  Entities are basically rows of data, similar to a row in a spreadsheet or a row within a database.  Each entity has a required primary key and a set of properties.  The properties are a name, typed-value pair, similar to a column.

Tables, Entities, and Properties

There are three core concepts to know when dealing with Windows Azure Tables; Table, Entities, and Properties.  For each of these core features of the Windows Azure Table Storage it is important to be able to add, possibly update, and delete the respective table, entity, or property.

Windows Azure Table Hierarchy;

  • Table – Similar to a spreadsheet or table in a relational database.
  • Entity – Similar to a row of data in a spreadsheet, relational database, or flat file.
  • Property – Similar to a cell in a spreadsheet or tuple in a relational database.

Each entity has the following system properties; a partition key, row key, and time stamp.  These properties are included with every entity and have reserved naming.  The partition and row key are responsibilities of the developer to insert into, while the time stamp is managed by the server and is read only.

Three properties that are part of every table;

  • Partition Key
  • Row Key
  • Time Stamp

Each table name must conform to the following rules; a name may have only alphanumeric characters, may not begin with a numeric character, are case-insensitive, and must be between 3 and 63 characters.

Tables are split across many nodes for horizontal scaling.  The traffic to these nodes is load balanced.  The entities within a table are organized by partition.  A partition is a consecutive range of entities possessing the same key value, the key being a unique identifier within a table for the partition.  The partition key is the first part of the entity’s primary key and can be up to 1 KB in size.  This partition key must be included in every insert, update, and delete operation.

The second part of the primary key is the row key property.  It is a unique identifier that should not be read, set on insert or update, and generally left as is.

The Timestamp property is a DateTime data type that is maintained by the server to record the entity for last modifications.  This value is used to provide optimistic concurrency to table storage and should not be read, inserted, or updated.

Each property name is case sensitive and cannot exceed 255 characters.  The accepted practice around property names is that they are similar to C# identifiers, yet conform to XML specifications.  Examples would include; “streetName”, “car”,  or “simpleValue”.

To learn more about the XML specifications check out the W3C link here:  http://www.w3.org/TR/REC-xml/.  This provides additional information about properly formed XML that is relatable to the XML usage with Windows Azure Table Storage.

Coding for Windows Azure Tables

What I am going to show for this code sample is how to setup an ASP.NET MVC Application using the business need of keeping an e-mail list for merges and other related needs.

I wrote the following user stories around this idea.

  1. The site user can add an e-mail with first and last name of the customer.
  2. The site user can view a listing of all the e-mail listings.
  3. The site user can delete a listing from the overall listings.
  4. The site user can update a listing from the overall listings.

This will provide a basic fully functional create, update, and delete against the Windows Azure Table Storage.  Our first step is to get started with creating the necessary projects within Visual Studio 2010 to create the site with the Windows Azure Storage and Deployment.

  1. Right click on Visual Studio 2010 and select Run As Administrator to execute Visual Studio 2010.
  2. Click on File, then New, and finally Project.  The new project dialog will appear.
  3. Select the Web Templates and then ASP.NET MVC 2 Empty Web Application.
  4. Name the project EmailMergeManagement.  Click OK.
  5. Now right click on the Solution and select Add and then New Project.  The new project dialog will appear again.
  6. Select the Cloud Templates and then the Windows Azure Cloud Service.
  7. Name the project EmailMergeManagementAzure.  Click OK.
  8. When the New Cloud Service Project dialog comes up, just click OK without selecting anything.
  9. Right click on the Roles Folder within the EmailMergeManagementAzure Project and select Add and then Web Role Project in Solution.
  10. Select the project in the Associate with Role Project Dialog and click OK.

The Solutions Explorer should have the follow projects, folders, files, and Roles setup.

Solution Explorer
Solution Explorer
  1. Now create controller classes called StorageController and one called HomeController.
  2. Now a Storage and Home directory in the Views directory.
  3. Add a view to each of those directories called Index.aspx.
  4. In the Index.aspx view in the Home directory add the following HTML.

[sourcecode language=”html”]
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<%:Html.Encode(ViewData["Message"])%>
<h1>
<%:Html.Encode(ViewData["Message"])%></h1>
This ASP.NET MVC Windows Azure Project provides examples around
the Windows Azure Storage usage utilizing the Windows Azure SDK.
<ul>
<li>
<%:Html.ActionLink("Windows Azure Table Storage", "Index", "Storage")%></li>
</ul>
[/sourcecode]

  1. In the Storage directory Index.aspx view add the following code.

[sourcecode language=”html”]
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<%: Html.Encode(ViewData["Message"])%>
<h1>
<%: Html.Encode(ViewData["Message"])%></h1>
[/sourcecode]

  1. In the StorageController add this code.

[sourcecode language=”csharp”]
using System.Web.Mvc;

namespace EmailMergeManagement.Controllers
{
public class StorageController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Windows Azure Table Storage Sample";
return View();
}
}
}
[/sourcecode]

  1. In the HomeController add this code.

[sourcecode language=”csharp”]
using System.Web.Mvc;

namespace EmailMergeManagement.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Windows Azure Storage Samples";
return View();
}
}
}
[/sourcecode]

Now the next step is to get our Models put together.  This section will include putting together the class for the Email Merge Listing Model, the repository class for getting the data in and out of the table, and the context object that is used for connecting to the actual Development Fabric or Windows Azure Table Storage.

Solution Explorer
Solution Explorer
  1. First add the following references; System.Data.Services.Client,  Microsoft.WindowsAzure.CloudDrive, Microsoft.WindowsAzure.Diagnostics, Microsoft.WindowsAzure.ServiceRuntime, and Microsoft.WindowsAzure.StorageClient to the project by right clicking on the References virtual folder for the EmailMergeManagement Project.
  2. Once you add these references create a class in the Models folder called EmailMergeModel and add the following code.  I’ve added some basic validation attributes to the Email, First, and Last Properties of the EmailMergeModel Class just so that it has a little more semblance of something you may actually see in real world use.

[sourcecode language=”csharp”]
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.WindowsAzure.StorageClient;

namespace EmailMergeManagement.Models
{
public class EmailMergeModel : TableServiceEntity
{
public EmailMergeModel(string partitionKey, string rowKey)
: base(partitionKey, rowKey)
{
}

public EmailMergeModel()
: this(Guid.NewGuid().ToString(), string.Empty)
{
}

[Required(ErrorMessage = "Email is required.")]
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9_\\+-]+(\\.[a-z0-9_\\-]+)*\\.([a-z]{2,4})$",
ErrorMessage = "Not a valid e-mail address.")]
public string Email { get; set; }

[Required(ErrorMessage = "First name is required.")]
[StringLength(50, ErrorMessage = "Must be less than 50 characters.")]
public string First { get; set; }

[Required(ErrorMessage = "Last name is required.")]
[StringLength(50, ErrorMessage = "Must be less than 50 characters.")]
public string Last { get; set; }

public DateTime LastEditStamp { get; set; }
}
}
[/sourcecode]

  1. Now add a class titled EmailMergeDataServiceContext for our data context.  This class provides the basic TableServiceContext inheritance that allows for creation of the table, entities, and properties through the Windows Azure SDK.
  2. Add the following code to the EmailMergeDataServiceContext Class.

[sourcecode language=”csharp”]
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace TestingCloudsWebApp.Models
{
public class EmailMergeDataServiceContext : TableServiceContext
{
public const string EmailMergeTableName = "EmailMergeTable";

public EmailMergeDataServiceContext(string baseAddress, StorageCredentials credentials)
: base(baseAddress, credentials)
{
}

public IQueryable EmailMergeTable
{
get { return CreateQuery(EmailMergeTableName); }
}
}
}
[/sourcecode]

  1. Create a class in the Models directory called EmailMergeRepository.  This is the class I will use to add the insert, update, and delete functionality.
  2. Now add a constructor and private readonly EmailMergeDataServiceContext member as shown below.

[sourcecode language=”csharp”]
private readonly EmailMergeDataServiceContext _serviceContext;

public EmailMergeRepository()
{
var storageAccount = CloudStorageAccount.
FromConfigurationSetting("DiagnosticsConnectionString");
_serviceContext =
new EmailMergeDataServiceContext(
storageAccount.TableEndpoint.ToString(),
storageAccount.Credentials);

storageAccount.CreateCloudTableClient().
CreateTableIfNotExist(
EmailMergeDataServiceContext.EmailMergeTableName);
}
[/sourcecode]

  1. Next add the select and get by methods to retrieve EmailMergeModel Objects.

[sourcecode language=”csharp”]
public IEnumerable<EmailMergeModel> Select()
{
var results = from c in _serviceContext.EmailMergeTable
select c;

var query = results.AsTableServiceQuery();
var queryResults = query.Execute();

return queryResults;
}

public EmailMergeModel GetEmailMergeModel(string rowKey)
{
EmailMergeModel result = (from c in _serviceContext.EmailMergeTable
where c.RowKey == rowKey
select c).FirstOrDefault();
return result;
}
[/sourcecode]

  1. Next add a method to add our custom date & time stamp for inserts and updates.

[sourcecode language=”csharp”]
private static EmailMergeModel StampIt(EmailMergeModel emailMergeModel)
{
// This is a sample of adding a cross cutting concern or similar functionality.
emailMergeModel.LastEditStamp = DateTime.Now;
return emailMergeModel;
}
[/sourcecode]

  1. Finally the delete, insert, and update methods can be added.

[sourcecode language=”csharp”]
public void Delete(EmailMergeModel emailMergeModelToDelete)
{
_serviceContext.Detach(emailMergeModelToDelete);
_serviceContext.AttachTo(EmailMergeDataServiceContext.EmailMergeTableName,
emailMergeModelToDelete, "*");
_serviceContext.DeleteObject(emailMergeModelToDelete);
_serviceContext.SaveChanges();
}

public void Insert(EmailMergeModel emailMergeModel)
{
_serviceContext.AddObject(EmailMergeDataServiceContext.EmailMergeTableName, StampIt(emailMergeModel));
_serviceContext.SaveChanges();
}

public void Update(EmailMergeModel emailMergeModelUpdate)
{
var emailMergeModelOld = GetEmailMergeModel(emailMergeModelUpdate.RowKey);
Delete(emailMergeModelOld);
Insert(StampIt(emailMergeModelUpdate));
}
[/sourcecode]

  1. At this point the Solution Explorer should have the following files and structure.
Storage Explorer
Storage Explorer

That’s it for part 1 of this two part series.  The next entry I’ll have posted this coming Monday, so stay tuned for the final steps.  🙂

Shout it

Monster Bits of WCF and Itty Bitty Bits of MVC

I’ve had the pleasure of working with WCF on three specific projects that have brought me to this blog entry.  I haven’t used WCF on only three projects, there are just three that have brought me to write this entry.  I’ve used WCF a lot, since back when it was a beta.  WCF is great when creating SOAP services and you aren’t too worried about the extra overhead.  WCF is great for what it does, for the ideas behind what it does.

But writing RESTful web services doesn’t seem to be its strong point.  On two huge projects WCF has basically been dropped, or so scaled back one really can’t honestly say that WCF is used, and either an alternate framework has been used or a LOT of custom code ends up being written.

The first time I used WCF to implement RESTful service was at Webtrends.  Albeit, there is a single service that returns all types of awesome reporting goodness, however to implement basic auth, logging, polling, and a whole host of other Enterprise Scale needs we had to custom roll most of it.  Keep in mind, when doing this the WCF REST capabilities were brand shiny and new, so there were a few issues to work out.  Now, maybe WCF could be used and a lot of it would be built in.  However as it was, we easily spent 60% of the time writing custom bits because WCF just didn’t have the right options with the right bindings.

But I digress, I recently implemented an architecture using RESTful services using WCF.  But now I’ve come to find myself dropping WCF because of the back and forth and going with ASP.NET MVC controller actions to return JSON instead.  With that, here’s to the lean mean controller actions rockin’ the JSON.  Here’s what I’ve done to port everything from WCF to MVC.

To see what I had done, except on a smaller scale, check out my previous blog entry on ASP.NET MVC with a WCF project smack in the middle of it.  This will give you an idea of what I was using the WCF services for, merely to provide JSON results via RESTful services to an ASP.NET MVC front end requesting data with jQuery.

This is how I’ve setup the controller to return JSON results via an action.

First start a new ASP.NET MVC Project and add a new controller.  Cleanup the controller so that you have the following in the controller.

[sourcecode language=”csharp”]
using System.Web.Mvc;

namespace RestWebServicesWithMvc.Controllers
{
public class ServicesController : Controller
{

}
}
[/sourcecode]

Now create a testing project to create your test first.  Remember to add the reference to the ASP.NET MVC project.  From here we can create the first test.

[sourcecode language=”csharp”]
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RestWebServicesWithMvc.Controllers;

namespace RestWebServicesWithMvc.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var controller = new ServicesController();
var result = controller.GetBiz();
Assert.IsNotNull(result);
}
}
}
[/sourcecode]

Now fill out the basic skeleton of the action in the controller.

[sourcecode language=”csharp”]
using System;
using System.Web.Mvc;

namespace RestWebServicesWithMvc.Controllers
{
public class ServicesController : Controller
{
public ActionResult GetBiz()
{
throw new NotImplementedException();
}
}
}
[/sourcecode]

Now we should have a good red running on our test.  Let’s create a business model class to return as our result next.

[sourcecode language=”csharp”]
namespace RestWebServicesWithMvc.Models
{
public class BizEntity
{
public string BizName { get; set; }
public string StartupDate { get; set; }
public int SalesThisMonth { get; set; }
}
}
[/sourcecode]

Now let’s return that object with some fake data.  First add [AcceptVerbs(HttpVerbs.Post)] to the action in the controller.  Then return a serializable object to the actual method as shown.

[sourcecode language=”csharp”]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetBiz()
{
return Json(
new BizEntity()
{
BizName = "Adron’s Code Workingz",
SalesThisMonth = 3429,
StartupDate = DateTime.Now.AddYears(-5).ToString()
}
);
}
[/sourcecode]

This is a quick starter.  There are a few dozen other options around this capability including other verb usage.  For many, this is all you need for your services, especially if their primary purpose is to communicate with a specific website and one doesn’t want the overhead of WCF.

Shout it

Exam 70-515 Focus Developing a Web Application by Using ASP.NET MVC 2

…and with this entry, I’ve skipped to the last section of the exam topics related to ASP.NET MVC 2.  Reading and studying the old viewstate based ASP.NET material was a bit rough, which I’ll be writing about in an upcoming entry.  For now, back to focusing on the test at hand.  The MVC Framework is pretty rock star awesome, so with that I’ll get to the notes.

Focus Point:  Developing a Web Application by Using ASP.NET MVC 2

Create Custom Route

  • ASP.NET Routing – ASP.NET enables you to use URLs that do not have a map to specific files in a Web Site.  Because the URL does not have a map to a file, you can use URLs that are descriptive of the user’s action and therefore are more easily understood by users.  Check out URL Patterns for more information (on the same page) and Adding Routes to an MVC Application.  Also for real world implementation you may want to know the difference between Routing and URL Rewriting.
  • Adding Constraints to Routes – In addition to matching the URL request to a route definition by the number of parameters in the URL, you can specify that values in the parameters meet certain constraints.  If a URL contains values that are outside the constraints for a route, that route is not used to handle the request.  You add constraints to make sure that the URL parameters contain values that will work in your application.  Constraints are defined by using regular expressions or by using objects that implement the IRouteConstraint interface. When you add the route definition to the Routes collection, you add constraints by creating a RouteValueDictionary object that contains the verification test. The key in the dictionary identifies the parameter that the constraint applies to. The value in the dictionary can be either a string that represents a regular expression or an object that implements the IRouteConstraint interface. If you provide a string, routing treats the string as a regular expression and checks whether the parameter value is valid by calling the IsMatch method of the Regex class. The regular expression is always treated as case-insensitive. For more information, see .NET Framework Regular Expressions.  If you provide an IRouteConstraint object, ASP.NET routing checks whether the parameter value is valid by calling the Match method of the IRouteConstraint object. The Match method returns a Boolean value that indicates whether the parameter value is valid.
  • Route Class – Provides properties and methods for defining a route and for obtaining information about the route.  The Route class enables you to specify how routing is processed in an ASP.NET application. You create a Route object for each URL pattern that you want to map to a class that can handle requests that correspond to that pattern. You then add the route to the Routes collection. When the application receives a request, ASP.NET routing iterates through the routes in the Routes collection to find the first route that matches the pattern of the URL.  Set the Url property to a URL pattern. The URL pattern consists of segments that come after the application name in an HTTP request. For example, in the URL http:www.contoso.com/products/show/beverages, the pattern applies to products/show/beverages. A pattern with three segments, such as{controller}/{action}/{id}, matches the URL http:www.contoso.com/products/show/beverages. Each segment is delimited by the / character. When a segment is enclosed in braces ( { and } ), the segment is referred to a URL parameter. ASP.NET routing retrieves the value from the request and assigns it to the URL parameter. In the previous example, the URL parameter action is assigned the value show. If the segment is not enclosed in braces, the value is treated as a literal value.  Set the Defaults property to a RouteValueDictionary object that includes values that are used if a parameter is missing from the URL or to set additional values that are not parameterized in the URL. Set the Constraints property to a RouteValueDictionary object that contains values that are either regular expressions orIRouteConstraint objects. These values are used to determine whether a parameter value is valid.
  • Route.Constraints Property – Gets or sets a dictionary of expressions that specify valid values for a URL parameter.  The Constraints property enables you to limit acceptable values for a URL parameter that is processed by a route. You assign a RouteValueDictionary object to the Constraints property. Each element in the RouteValueDictionary object contains the name of a parameter and one of the following:
    • A string that defines a regular expression. The regular expression is case-insensitive.
    • An object that implements the IRouteConstraint interface and that includes a Match method.

The following example is from the MSDN, which shows allowed methods of GET and POST.

[sourcecode language=”csharp”]
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
string[] allowedMethods = { "GET", "POST" };
HttpMethodConstraint methodConstraints = new HttpMethodConstraint(allowedMethods);

Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
reportRoute.Constraints = new RouteValueDictionary { { "httpMethod", methodConstraints } };

routes.Add(reportRoute);
}
[/sourcecode]

Create Controllers and Actions

  • Controller and Action Methods in MVC Applications – The ASP.NET MVC Framework maps URLs to classes that are referred to as controllers.  Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic.  A controller class typically calls a separate view component to generate the HTML markup for the request.  The base class for all controllers is the ControllerBase class, which provides general MVC handling.
  • Two great articles;  MSDN Magazine titled Building Web Apps without Web Forms and there is the What’s New section on the ASP.NET MVC Site.
  • Create an action – You add a new action to a controller by adding a new method to the controller. These methods must meet these requirements:
    • Must be public
    • Cannot contain a static method
    • Cannot be an extension method
    • Cannot be a constructor, getter, or setter
    • Cannot have open generic types
    • Cannot contain out or ref parameters
    • is not a method of the controller base class.
  • Create a Controller – This tutorial covers creating a controller including the menu options and scaffolding, etc.
  • Action Filtering in MVC Applications – In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, such as clicking a link or submitting a form.  For example, when a user clicks a link, a request is routed to the designated controller, and the corresponding action method is called.  ASP.NET MVC provides action filters that are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.

MVC 2 Template Project

Structure an ASP.NET MVC Application

  • MVC Framework and Application Structure – In an ASP.NET website, URLs typically map to files that are stored on disk (usually .aspx files).  These .aspx files include markup and code that is processed in order to respond to the request. The ASP.NET MVC framework maps URLs to server code differently than an ASP.NET Web Forms page. Instead of mapping URLs to ASP.NET pages or handlers, the framework maps URLs to controller classes. Controller classes handle incoming requests, such as user input and interactions, and execute appropriate application and data logic, based on user input. A controller class typically calls a separate view component that generates HTML output as the response. The ASP.NET MVC framework separates the model, view, and controller components.
  • Global URL Routing Defaults see below (from MSDN Article)

[sourcecode language=”csharp”]
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);

}

protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
[/sourcecode]

Create and Customize Views

Using the begin BeginForm Helper

[sourcecode language=”html”]
<% using(Html.BeginForm("HandleForm", "Home")) %>
<% { %>
<!– Form content goes here –>
<% } %>
[/sourcecode]

Using it declaratively…

[sourcecode language=”html”]
<% Html.BeginForm(); %>
<!– Form content goes here –>
<% Html.EndForm(); %>
[/sourcecode]

Using the Checkbox Helper

[sourcecode language=”html”]
<%= Html.CheckBox("bookType") %>
[/sourcecode]

Using the DropDownList Helper

[sourcecode language=”html”]
<%= Html.DropDownList("pets") %>
[/sourcecode]

[sourcecode language=”csharp”]
List<string> petList = new List<string>();
petList.Add("Dog");
petList.Add("Cat");
petList.Add("Hamster");
petList.Add("Parrot");
petList.Add("Gold fish");
petList.Add("Mountain lion");
petList.Add("Elephant");

ViewData["Pets"] = new SelectList(petList);
[/sourcecode]

Using the RadioButton Helper

[sourcecode language=”html”]
Select your favorite color:<br />
<%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
<%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
<%= Html.RadioButton("favColor", "Red", false)%> Red <br />
<%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
<%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
<%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
<%= Html.RadioButton("favColor", "Green", false)%> Green
[/sourcecode]

Using the Textbox Helper

[sourcecode language=”html”]
Enter your name: <%= Html.TextBox("name") %>
[/sourcecode]