Learning: Part 2 - ASP.NET MVC 2.0 with Visual Studio 2010 Beta 2
Please make sure you’ve seen my previous blog post because this one continues on the project built.
In this post, we’ll explore a couple of more options to learn more about MVC. There are some great starting points right here.
https://www.asp.net/mvc/learn/
I will go through some of these, briefly. I will adapt the “HelloWorld” from my previous blog entry, which shows you how to setup and get started with your first application.
Creating Custom Routes
The goal of creating custom routes is to make interaction with your web site more intuitive and natural. It should also map well for search engines.
Scott Guthrie said it best at https://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
- Having the ability to use URL mapping rules to handle both incoming and outgoing URL scenarios adds a lot of flexibility to application code.
- It means that if we want to later change the URL structure of our application (for example: rename /Products to /Catalog), we could do so by modifying one set of mapping rules at the application level - and not require changing any code within our Controllers or View templates.
Imagine that you sell car parts:
- Here is a URL you may wish to create a custom route for:
Our goal is to support the following:
https://www.mygoofycarparts.com/Brakes/Disc
So here are the 4 steps we will take
How we would setup our own view and controller (basic starter kit)
Step 1 - Edit global.asax and edit route table
The whole point here is to get us to the right controller / action method / custom view combination that we dream up based on url.
We want to support the url https://blah_blah.com/Brakes/Disc. That means we need to add our own controllers, action methods, and views.
Notice lines 27-31 where we added an additional routing table. You can start to see support for the https://blah_blah.com/Brakes/Disc url.
https://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx is a link to Scott Guthries blogy about the syntax used on on line 30 below. It is called object initializers. |
Code Snippet
- //=========================================================
- // This is global.asax
- //=========================================================
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace HelloWorld
- {
- // Note: For instructions on enabling IIS6 or IIS7 classic mode,
- // visit https://go.microsoft.com/?LinkId=9394801
- public class MvcApplication : System.Web.HttpApplication
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- // Pass the "route name", the "url with parameters", the "defaults"
- // This will mean that I need a controller called BrakesController
- // I will also need an action method to support whatever url pattern I support
- // For example: https://brunocarparts.com/brakes/disc
- // I need a method called "disc"
- routes.MapRoute(
- "CarParts",
- "Brakes/{brakeType}",
- new { controller = "Brakes", action = "Disc" }
- );
- 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);
- }
- }
- }
Step 2 - Add controller and action method
One of the first steps you need to do to get your url supported with the MVC plumbing is to add a custom controller.
It is easy to do because it is built into Visual Studio 2010 Beta 2. Once we add the controller (BrakesController) we will also need to add an action method called "Disc()".
Make sure your selections as follows:
- Controller Name = BrakesController
- Add action methods for Create, Update, Details = True = Yes = CheckMark
Notice that lines 19-22 support the Disc part of https://blah_blah.com/Brakes/Disc
Methods Provided by MVC Framework | Our Custom Method(s) |
Index() | Disc() |
Details() | |
Create() | |
Edit() |
We will cover Details(), Create(), Edit() in a future post.
Code Snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace HelloWorld.Controllers
{
public class BrakesController : Controller
{
//
// GET: /Brakes/
public ActionResult Index()
{
return View();
}
public ActionResult Disc()
{
return View();
}
//
// GET: /Brakes/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Brakes/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Brakes/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Brakes/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Brakes/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Step 3 - Add view (in folder structure)
After we have added the controller and the action method, we need to next add our own custom view. Later we will play with the model and add database support.
Call the new folder Brakes. Make sure you create the folder underneath the Views folder.
Afterall, https://blah_blah.com/Brakes/Disc should take you to a database query that shows "Disc Brakes."
We can worry about CRUD later (Create, Read, Update, Delete).
Now add the view. Later we will enhance this view to cooperate with the model object to display data. In particular, to display disc brakes.
Call the view “Disc” to support https://blah_blah.com/Brakes/Disc.
Modify the code a little bit to validate the the view we create is the view we see.
This is the default view of Disc.aspx
Add your own code in the designer as follows for Disc.aspx (our view to support https://blah_blah.com/Brakes/Disc.
Step 4 - Run and validate
Finally, we want to run the application with https://blah_blah.com/Brakes/Disc and see our view popup with our own custom message to show the whole thing is working together correctly.
Run the final program. But we will need to edit the url.
This is the wrong url:
We’ve been talking about:
- https://blah_blah.com/Brakes/disc, or, more accurately,
- https://localhost:19078/Brakes/Disc
Notice the url we want: https://localhost:19078/Brakes/Disc
This represents the final step for this post. Hope you enjoyed it.
Here is the code: