IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

Introduction to Microsoft MVC.Net

Get Started with Microsoft MVC.Net

By , Written on in C#

Introduction to Microsoft MVC.Net

1,788 words, estimated reading time 9 minutes.

Introduction to the Microsoft ASP.Net MVC framework showing you everything that you need to build an application using this tool.

Before we dive into the Microsoft MVC.Net framework, let's first talk a little bit about why it exists. Traditional ASP.NET Web Forms was a way to make developing for the web similar to developing desktop appliactions using forms. When you click a button on a ASP.NET Web Form, an event is triggered in the code behind which performs an action. This is the same way in which Windows Forms work. Web Forms abstracted away the technicalities of HTML requests, and even HTML markup. As time moved on, people didn't want this abstraction any more, and looking at other web development methodologies and frameworks, Microsoft decided to adopt the Model View Controller design pattern. Microsoft MVC.Net does not replace web forms, it is another way of doing something. There is still C# of VB.Net code behind, Sessions, Caching and Requests all work in the same way.

The MVC Design Pattern

The MVC Design Pattern has actually been around for decades and across many different platforms and technologies, everything from Smalltalk to C++ to Java.

The general idea with Microsoft MVC.Net is that you'll have a component called the View which is solely responsible for rendering the user interface. That view will talk to a Model, and that model contains all of the data that the view needs to display. Views generally don't have any logic inside of them, with the exception of some HTML and some expressions of where to take pieces of data from the model into the correct places in the HTML template. It's is the role of the controller to tie things together that orchestrates everything. The controller is responsible for building the model, performing any logic and selecting the view. It never interacts with the user interface. That's the job of the view. The controller never holds any data or state inside of it. That's the job of the model.

Microsoft MVC.Net Architecture
Microsoft MVC.Net Architecture

Web Forms versus Microsoft MVC.Net

If you've already been using ASP.NET Web Forms, you may be wondering how the MVC pattern changes the high level view of how stuff works inside of ASP.NET. With Web Forms, you'll have an incoming HTTP request which will ask for a specific ASPX page. That request is directed to a specific file on the file system and ASP.NET is going to instantiate a class that represents that page and ask it to execute. Inside of here you can have things like a page load method, the page pre-render method, the page unload method. You can perform all your processing inside of that page. The HTML view contained within that page is really bound to that page, there is little separation between the HTML view and the logic code behind. That makes code re-use and unit testing far more complicated.

In Microsoft MVC.Net, things work a little bit differently. The incoming HTTP request will be routed to the MVC framework, which is going to do is first route that request to a controller. That controller is going to be a class that you write, and it isn't bound to any particular ASPX file. It is pure C# or VB.Net code (or whatever code you choose to write in). The controller class has regular public instance methods like any other class. There's no page load event handler that has to be invoked. There's simply methods that return results and they take parameters.

Creating an Application

So how does MVC know what controller and what method to call? Well, that's all handled by routing. By default, the standard URL structure of an MVC site takes the form of http://domainname.com/home/index. In that example, Microsoft ASP.Net will instantiate an instance of the class for the home controller, and execute a method called index. There are some naming conventions that must be observed. The controller must be named HomeController (home, with Controller as a suffix). Controller classes must reside within a folder called Controllers.

A really simple controller would look something like this.

  1.  
  2. public class HomeController: Controller
  3. {
  4. public ActionResult Index()
  5. {
  6. return View();
  7. }
  8. }

In the example above we can see that the HomeController extends the Controller class, it has a method called Index which returns an ActionResult. Almost all controller actions will return an ActionResult, usually the View or a redirect.

The controller must have a view. Views are contained within a folder called Views, and a sub folder with the same name as the controller. The file is named the same as the method name. In this example it would be ~/Views/Home/Index.cshtml

So now that has been explained, lets fire up Visual Studio and create an MVC application.

Start off by clicking File > New then selecting New Project. From the screen that appears browse into Templates > Windows > Web and select ASP.NET Web Application. Give your project a name and set the location. In the next window, select MVC. Click ok to create the project. When the project is done creating you should have a solution similar to the one on the right.

You should notice some familiar folders from Web Forms, as well as the Controllers, Models and Views folders. If you expand the folders and look inside, you should see the HomeController.cs and the view for the Homepage.

MVC Application Solution
MVC Application Solution

If you run the application you can browse to the homepage, about and contact pages. The Index method of the HomeController class is the default view for each controller class. You can also see methods for About and Contact. The About method places some data in the ViewBag object. This is used to temporarily store some data which can be used in the View.

If you look in the Views/Home folder you can see the views for Index, Contact and About. These are implicitly called when you call View(); from a controller method. You can also explicitly invoke a view by passing it as a parameter e.g. View("Contact");

Controllers have the responsibility for processing data and performing logic. Although you can pass data to the view using the ViewBag, for more than a couple of items it's best to use a model. A model is just a class with a series of public properties. There is no naming convention to models, you can name them anything you want, although common suffixes include Model or ViewModel simply to identify them as such.

  1. public class DemoModel
  2. {
  3. public string SampleText { get; set; }
  4. }

To pass a model from a controller to a view, simply pass it as a parameter to the View() method.

  1.  
  2. public class HomeController: Controller
  3. {
  4. public ActionResult Index()
  5. {
  6. DemoModel model = new DemoModel();
  7. model.SampleText = "Hello World";
  8. return View(model);
  9. }
  10. }

View pages are equivalent to ASPX pages, although they use slightly different syntax and a different render engine called Razor.

Razor syntax begins with an @ symbol to prefix commands, for example @Html is the razor HTML helper. A simple view is shown below.

  1. @{
  2. ViewBag.Title = "Home Page";
  3. }
  4.  
  5. <div class="jumbotron">
  6. <h1>ASP.NET</h1>
  7. <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
  8. <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
  9. </div>

To use a model in the view, make a model declaration in the header of the file.

  1. @Model DemoApplication.Models.DemoModel
  2. @{
  3. ViewBag.Title = "Home Page";
  4. }
  5.  
  6. <div class="jumbotron">
  7. <h1>ASP.NET</h1>
  8. <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
  9. <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
  10. </div>

Now you can access the properties of the model using the @Model helper.

  1. @Model DemoApplication.Models.DemoModel
  2. @{
  3. ViewBag.Title = "Home Page";
  4. }
  5.  
  6. <div class="jumbotron">
  7. <h1>@Model.SampleText</h1>
  8. <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
  9. <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
  10. </div>

Unless you are creating a very limited application, you will want to capture some kind of user input in a form of some kind. MVC makes this very easy using a model and the HTML helpers.

Firstly, create a simple form in the view using the HTML helper methods.

  1. @using (Html.BeginForm())
  2. {
  3. @Html.AntiForgeryToken()
  4. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  5. @Html.TextBox("Name")
  6. @Html.Password("Password")
  7. <input type="submit" value="Sign In">
  8. }

The first line creates a form, it automatically handles the open and close tags and the attributes of the form. The default is to post back to the controller method. The anti forgery token is used to help protect against cross site scripting. The process is automatic. The validation summary should be familiar from web forms, it simply shows errors from the form submit. Next there is a text box field and a password field and a submit button.

The controller action to handle this and capture the results will look like the method below.

  1. [HttpPost]
  2. public ActionResult Index(string Name, string Password)
  3. {
  4. DoSomeAction(Name, Password);
  5. return View();
  6. }

The HttpPost attribute on the method indicates that this method can only be accessed when a HTTP POST is sent to it. The default is GET. The Index method accepts parameters for the two text boxes, Name and Password. MVC automatically extracts the data from the form submit and places them in the properties for you.

You can also show a form for a model for more advanced data capture. In this case instead of @Html.TextBox, use @Html.TextBoxFor and pass in the model property you wish to use.

  1. @using (Html.BeginForm())
  2. {
  3. @Html.AntiForgeryToken()
  4. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  5. @Html.TextBoxFor(x => x.SampleText)
  6. <input type="submit" value="Submit">
  7. }

The controller action method can now accept the model as a parameter.

  1. [HttpPost]
  2. public ActionResult Index(DemoModel data)
  3. {
  4. DoSomeAction(data.SampleText);
  5. return View();
  6. }

Last updated on: Wednesday 21st June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Further Reading
Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.