Monday, March 23, 2009

Getting Started with ASP.NET's MVC (Model View Controller)

  1. Download and install MVC 1.0.
  2. Create the MVC project.
  3. Startup VS.NET 2008.
  4. Click on File-->New-->Project.
  5. Choose the Web project type.
  6. Choose the ASP.NET MVC Web Application
  7. Click on OK.
  8. Create the Controller.
  9. In the Solution Explorer, right click on the Controllers tab, then click on Add-->Controller.
  10. Name it Test, then click on OK.
  11. Open up the Test1Controller.cs class file, in the Controllers folder.
  12. Modify the Index() method so that it looks like this: public ActionResult Index(int ID) { return View(); }
  13. Save it.
  14. Create the action.
  15. Right click inside of the Index method, then click on Add view...
  16. Leave the defaults, then click on Add.
  17. In the Views folder, notice that the Index.aspx page was added to the Test1 folder.
  18. Press Ctrl-Shift-B to compile the application.
  19. Press Ctrl-F5 to run the application.
  20. The following URL will map to the Test1 controller, action, and view: http://localhost:????/Test1/Index/1
    Test1 is the controller. Index is the action, defined as a method inside the controller class, and 1 is the ID integer passed to that method. When that URL is process, the following method is called: Test1Controller.Index(1)
  21. To make the ID integer options, convert the type from int to a nullable integer: int? public ActionResult Index(int? ID) { return View(); }
  22. After that, you should be able to omit the ID, like this: http://localhost:????/Test1/Index/ or http://localhost:????/Test1/
  23. Remember to compile the application every time a code change is performed.

No comments: