ASP.NET MVC

ASP.NET MVC is still a relatively new technology for creating web pages. Unlike Web Forms, it kind of goes back to the old classic ASP world, where HTML and code gets mixed up in one file.

The only thing the ASP.NET MVC tries to separate is the data from its presentation. It uses the MVC – model, view, controller approach. The data is represented by a model (C# class). The view is the HTML file that takes care of the data presentation. The controller simply ties model and view together by handling the http requests and responses.

ASP.NET MVC will not give you a drag and drop kind of development – just like the one we saw with ASP.NET Web Forms. You will need to type the HTML yourself. This takes a bit away from the development productivity at the beginning but will give you an enormous flexibility as to how your HTML code can actually look like. This is essential for careful preparation of a client side scripting (AJAX, client JavaScript frameworks, etc.) as well as for Search Engine Optimization (SEO).

In this section we will see how to create a simple ASP.NET MVC web application, featuring only a textbox and two buttons. We will use this application to explain the basics of the ASP.NET MVC technology. Later, we will look at a more complex ASP.NET MVC application with a database connection and a client side scripting.

Simple ASP.NET MVC Application

To create a new ASP.NET MVC Application, start Visual Studio, go to “File” menu and select “New” > “Project”. A new dialog window appears. Select “Web” on the left and then “ASP.NET Web Application”. Now type the name of the application and click “OK”:

New Project 1

In the following window, select that we want to start with an empty application and that we would like to use the “MVC” technology:

New Project 2

Once you click “OK” a new ASP.NET MVC application will be created.

The project does not include any controllers yet. Add a new controller by right-clicking on the “Controllers” folder in the Solution Explorer and selecting “Add” > “Controller…”. In the new window, select the “MVC 5 Controller - Empty” and click “Add”:

Add Controller 1

In the new window, name the new controller as “HomeController” and click “Add” again:

Add Controller 2

This will create the “HomeController” code file and a new “Home” folder under the “Views” folder:

Solution Explorer After Controller

The default content of the HomeController file is quite simple. It only contains one method – Index. By convention, these methods get executed whenever there is a request for the “Controller/Method” URL. In our case the Index method will get executed for the following URL: “http://localhost:port/Home/Index”. As of now, the controller performs only one action – it returns the default view (the “Index” view):

Home Controller

We will need to create the “Index” view now. If we failed to do that, we would get an error from the Controller that the view is missing. To create the “Index” view, right-click the new “Home” folder under the “Views” folder and select “Add” > “View…”. In the new window, name the view as “Index”, choose an empty template without model and click “Add”:

Add View

This action not only created our “Index” view but it also created a “_ViewStart” and “_Layout” files:

Solution Explorer After View

The “_ViewStart” file specifies the default layout file to be used. It points to our “_Layout” file:

ViewStart File

The “_Layout” file provides the basic template that every view is going to use. You can think of it as a master page:

Layout File

The “_Layout” file sets up an HTML 5 structure and uses the Twitter Bootstrap for layout. In the second half of the file, you will find the “@RenderBody()” call. That is actually a placeholder for the content of our views. When a view is being returned from a controller, it will be placed inside the “_Layout” page.

The “Index” view itself is pretty straightforward now. It just sets the page “Title” and renders one H2 tag:

Index View

The Title in the “Index” view is specified through the “ViewBag” property. The “_Layout” page reads this property and puts its content within the HTML Title tag. The “ViewBag” is a dynamic property and you can easily use it to pass any data between views, layouts or controllers. Remember that it only lives for the duration of the request, though.

So far you have already seen how C# code can be mixed with the HTML code through the use of the at (@) sign. This markup is called “Razor” and it is one of the greatest and most powerful features of the ASP.NET MVC technology. You will see more examples of its usage later on.

We are now ready to test our project by running it. By hitting F5, Visual Studio starts the “IIS Express”, opens a new web browser window and navigates it to the root of our application. Since “Home” is the default controller and “Index” is the default action (method), we should see the “Index” view displayed:

Index View - running

Should you want to change the default controller or the default action, look in the “RouteConfig.cs” file inside the “App_Start” folder.

Let us now move forward with our example. Our index page will contain a textbox. Once the user types their name in it, the application should greet them.

At this point it is important to realize that in accordance with the MVC approach, the user’s name itself is considered the view data and that it should be placed inside a separate model.

To create a new model, right click the “Models” folder and add a new class. Name the class “PersonModel.cs”.

Once you have the model class created, add a single auto-implemented property in it, our Name property:

public string Name { get; set; }

Finally we have everything ready to make some changes to our view and our controller. Replace the view code with the following:

@using MyCSharpDotNet.SimpleAspMvcApplication.Models;
 
@model PersonModel
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
 
<p class="text-success">@ViewBag.Greeting</p>
 
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control input-sm" })
    </div>
    
    <input type="submit" value="Click me 1" class="btn btn-default" />
}
 
<button
    class="btn btn-default"
    onclick="alert('Hi ' + $('#Name').val() + '!')">
    Click me 2
</button>

You can see the view specifies our PersonModel class as the model. In addition, the form itself and its textbox are created through some MVC helper methods. These helper methods make sure the controls are bound to the model.

Going forward, we also have two buttons. The first button is a submit button that sends the form data as a POST request to the server. The server will take the name, place the greeting inside the ViewBag.Greeting property and send the page back to the client.

The second button does not use the server at all, it just uses jQuery to show the greeting in a message box on the client.

We also need to make some changes in the controller as the server needs to be able to process the POST request coming from the client. Add the following method to our controller:

[HttpPost]
public ActionResult Index(PersonModel model)
{
    ViewBag.Greeting = "Hi " + model.Name + "!";
 
    return View();
}

This controller method fires automatically when a POST request comes. It simply takes the model as a parameter and creates a greeting in a new ViewBag.Greeting property. The method returns the same view back – effectively showing the greeting.

We now have everything set up and we can run the application by pressing F5.

You can test the application by typing your name in the textbox and clicking either of the buttons. The first button will send a POST request back to the server and returns HTML with the greeting already embedded:

Greeting 1

The second button will simply show the greeting through the use of jQuery:

Greeting 2

The complete Simple ASP.NET MVC Application is available for download.

Advanced ASP.NET MVC Application

To see how a drop down list and a table can be used, you can also examine the Advanced ASP.NET MVC Application. There you will see how you can build an application similar to the one we have already built in the Web Forms topic:

Advanced ASP.NET MVC Application – running

As it is much easier to use AJAX and other web technologies with ASP.NET MVC, the example also shows how to connect ASP.NET MVC and AngularJS – one of the most popular JavaScript frameworks. Feel free to examine the code by yourselves.

Other ASP.NET MVC Examples

Below, you will find links to several ASP.NET MVC projects. Each project demonstrates one ASP.NET MVC topic:

This is the last page of this topic.

Go up to: Web Applications


Should you have any questions or found a mistake that needs correcting, feel free to send an email to: info [at] mycsharp [dot] net


Advertisements :