MVC 4 - Pt 1 : Models Views Controllers, Oh My! A quick intro to MVC...

So I've begun to explore the world of .NET MVC (Models, Views, and Controllers). I've been taking a course on PluralSight called Building ASP.NET MVC 4 Web Applications by Scott Allen. I know a lot of people, especially Microsoftians like me, who fear change, have been wondering what all the hubbub is about regarding this MVC vs. Web Forms thing. Well, I do understand now why MVC is a much better and more extensible design pattern. Let me dispel some of the myths right now! 

Do I need to learn a completely new programming language in order to use MVC? NO!
MVC is built on the tried, true and proven ASP.NET runtime. One of the most popular approaches to building MVC applications is creating strongly typed models, basically created an object and declaring an instance of that object in an Action method. Now, how many times have us .Netters created a class in C#? About a gazillion, right? So, it's using our existing knowledge and skills and applying to this new design pattern. Pretty cool, huh? Example:

So, in our newly created ASP.NET MVC 4 Web Application project in Visual Studio, we:

1. right-click on the Models folder.

2. Add a new class, call it something like AboutModel. Add > Class > AboutModel.cs

3. Add 2 properties in the class. Note - use a code snippet "prop" and then hit Tab twice to have VS fill in the property line.

public class AboutModel
 public string Name { get; set; }
 public string Location { get; set; }

4. Go to HomeController. This is the default controller where the default route is defined. All other controllers fall under the HomeController. Declare a new instance of AboutModel as follows... Note - AboutModel is in a different namespace than Controllers so you need to type out the entire class name or add a using statement.

5. Add data to the model object and pass model object instance to the View and return it! Voila!...but wait, we need to tell the View to render the model object instance.

Here is how the code looks in the HomeController About() method...

public ActionResult About()
 var model = new AboutModel();
 model.Name = "Katherine Hambley";
 model.Location = "Wisconsin, USA";
 return View(model);

6. Open the About.cshtml file in the Views/Home folder. In About.cshtml, first step is to tell the View about this model, add a directive at the top of the About.cshtml. Then, add your object access statements, @Model.Name and @Model.Location where you want them to appear on the page. 

@model OdeToFood2.Models.AboutModel
 ViewBag.Title = "About";
 Location: @Model.Location

Then, do another build and a refresh of the browser page, and the page is built using a strongly typed model.


Add comment