ASP.NET MVC3 Razor With jQuery For Beginners

Posted by imomins on June 5, 2012 at 10:05 AM

Table of content

Introduction

In this article you will find the simplest way to create your first ASP.NET MVC application. This is a tutorial for absolute beginners to ASP.NET MVC. The only prerequisite for following this tutorial is that you know how to use Visual Studio, and understand HTML and C# syntax. Also, I will show you briefly how you can use some jQuery plug-ins so it would be helpful if you know some jQuery syntax. If you are not familiar with jQuery, it is not a problem, you can just skip those parts because they are optional enhancements.

Background

What is MVC (Model-View-Controller)? MVC is a simple architecture where all components are separated into three classes:

  1. Model - Classes that contain data that will be shown to the user.
  2. View - Components that will display the model to the user.
  3. Controller - Components that will handle any interaction with the user.

In the web framework, the user will enter some URL to the ASP.NET MVC application, and the controller, model, and view will handle this request and return the HTML back to the user. The interaction between the browser and the server that has model, view, and controller components is shown in the following figure:

This simple scenario of processing an MVC request is described in the following steps:

  1. The user enters in the browser some URL that is sent to the server, e.g., http://localhost/Product/List.
  2. The user request is analyzed by the framework in order to determine what controller should be called.
  3. The Controller takes the parameters that the user has sent, calls the model to fetch some data, and loads the model object that should be displayed.
  4. The Controller passes the model object to the view.
  5. The View gets data from the model, puts it into the HTML template, and sends the response back to the user browser.
  6. The browser shows the HTML that is received from the server.

In this example, I will show how you can create a simple application that allows you to list and manage user details using ASP.NET MVC using the Razor syntax.

First, what is Razor? When you create a view component that translates C# data objects to HTML view, you can use several template syntax. Razor is one nice and clean syntax for combining C# and HTML code. In the following listing, you can see a simple example of the Razor syntax:

@{
 string name = "Jovan";
 var dateOfBirth = new { Day = 8, Month = 12, Year = 1980 }; 
 string[] skills = new string[] { "MVC",  "C#", "JQuery", "ASP.NET" };
}

<h2>@name</h2>
<p>Born in year: @dateOfBirth.Year</p>
<ul>
@foreach(skill in skills){
 <li>skill</li> 
}
</ul>

In the first part, I have defined a few C# variables, and then I have injected them into the HTML code. The resulting HTML output is shown in the following listing:

<h2>Jovan</h2>
<p>Born in year: 1980</p>
<ul>
 <li>MVC</li>
 <li>C#</li>
 <li>JQuery</li>
 <li>ASP.NET</li>
</ul>

As you can see, C# code will be discarded and only values from that code will be injected in the HTML template. Putting C# data into HTML with Razor syntax is easy - just put the name of the C# variable with the @ prefix. This works both with simple types and object fields. Even if you have more complex processing such as outputting the list of elements with some loop, the syntax is very clean.

If you are not familiar with Razor, you can see a quick reference here or a full reference on the ASP.NET MVC site.

Note that in this example, C# data is defined directly in the view. However, in the real code, C# data will come from the model that is provided by the controller (see figure above).

Using the code

To start with this code, you will need to have Visual Studio or at least Web Developer. If you do not have it, you can install it from the ASP.NET MVC site. There you can find all the necessary prerequisites for installing the MVC framework.

Once you install Web Developer, creating an MVC application is easy. Just go to File/New Project, select ASP.NET MVC Web Application, and the wizard will walk you through the setup process.

Here you should put the name of your project and determine where it will be placed. You can use the default settings if you want. The following sections will explain the structure and elements of the created MVC project.

MVC Project structure

When you create your MVC web application, it will be organized in the following folders:

  • Model containing your model classes.
  • Controller where are placed classes named as <CONTROLLER-NAME>Controller. These classes contain the action method that will be called when an HTTP request is sent.
  • Views - In this folder are placed template files that will be used to generate HTML as a response. Views are partitioned into subfolders. Each controller has its own subfolder named the same way as the controller where the controller's views are placed.
  • CSS files and images will be placed in the Content folder.
  • JavaScript files will be placed in the Scripts folders.

An example of that kind of structure is shown in the following figure:

In this figure, you can see all the components described above. We have two controllers User and School and their views in the /Views/School and /Views/User folders. Views that are placed in the /Views/Shared folder are shared among all controllers and views. Note that views have a .cshtml file extension. This means that they are using Razor syntax for view templates (this syntax is used in this tutorial).

Model

Model can be any class that defines a data structure that will be shown to the user. It can be a plain C# class, an Entity Framework model generated from a database, even a DataSet (although it is not recommended to use it in MVC). In this example, I will use a plain list of objects as a simulation of the data repository. The examples in this article will display a table of users from the list, show/edit details of a user object from the list, and enable you to add/delete users from the list. The Model class used in the application is shown in the following listing:

public partial class User
{
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Country { get; set; }
    public string Email { get; set; }
    public DateTime DoB { get; set; }
    public bool IsActive { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public int Rating { get; set; }
}

This example will not use persistent data storage (e.g., database). I will put the User object in a plain list and the application will use it to show user data. An example of that kind of "repository" is shown in the following example:

public class UserRepository
{
        public static List<User> Users = new List<User>();
}

Although I will not explain any advanced data access techniques, I will use some simple LINQ queries to find user data from the list. The following listing shows LINQ queries that find users:

var user = userList.First(x => x.UserID == id); 
var bestUsers = userList.Where(x => x.Rating > 8);

The first line of code finds the first object in the user list that has property UserID equal to the ID variable (i.e., finds a user by ID). The second line finds all the users with rating greater than 8.

The form parameter => expression is an inline function (lambda expression) that is used to define the criterion for finding users from the list. It is just a shorter version for the inline function that would look like:

function(parameter){ return expression; }

You can find more information about LINQ queries in the Using LINQ Queries article.

View

View is a plain file that defines a template that will be used to show Model data. In the simplest scenario, you can imagine View as a plain HTML code where are placed positions where you will inject Model properties. An example of that kind of View is shown in the following listing:

<fieldset>
    <legend>User</legend>
    <div class="display-label">Name</div>
    <div class="display-field">@Model.Name</div>
    <div class="display-label">Address</div>
    <div class="display-field">@Model.Address</div>
</fieldset>

In this Ciew is defined an HTML structure that will be shown to the user, and the places where the Model data will be placed. The example will inject the Model Name and Address properties into the HTML code. The syntax @Model.<<PropertyName>> defines a place where the Model property will be placed in the View. If you have values "Jane Smith" for name and "Regent street 12, London" for address, the following HTML output will be generated:

<fieldset>
    <legend>User</legend>
    <div class="display-label">Name</div>
    <div class="display-field">Jane Smith</div>
    <div class="display-label">Address</div>
    <div class="display-field">Regent street 12, London</div>
</fieldset>

When you generate complex form elements such as INPUT, TEXTAREA, etc., you can use the same approach as the one in the previous example. You can put HTML code for INPUT and inject some property of the Model directly in the value attribute. An example is shown in the following listing:

<input name="address" id="address"  value="@Model.Address" class="medium-size" />

However, instead of plain HTML, you can use a number of built-in Extension Methods of the HTML class.

@Html.TextBox( "address", Model.Address)
@Html.TextBoxFor(  model => model.Address )

The first parameter is the name/ID for the textbox, and the second parameter specifies the value it should have. This helper method will render an INPUT tag and the type="text" attribute. In the second example is used the TextBoxFor method where is passed a lambda expression that specifies the Address property. In this case we do not need to explicitly specify name/id of the input field - the helper method will take it from the property name. There are other helper methods that can be used to generate other form elements:

  • Html.DropDownListFor()
  • Html.CheckboxFor()
  • Html.RadioButtonFor()
  • Html.ListBoxFor()
  • Html.PasswordFor()
  • Html.HiddenFor()
  • Html.LabelFor()

You can also add your own methods that render some of your custom HTML such as Html.Table(), Html.Calendar(), etc. You can see more details in Creating custom helpers on the MVC site. You can also generate HTML without specifying the type using the Html.DisplayFor and Html.EditorFor methods. An example is shown in the following listing:

@Html.DisplayFor( model => model.Address )
@Html.EditorFor(  model => model.Address )

In these methods, we have not specified the type of input at all, because it will be determined based on the type of the property that should be shown. As an example, if the type of the property is string, EditorFor will generate text input. A more interesting example is when you pass some object to EditorFor. By default, the EditorFor method will generate an INPUT element for each property in the object based on the type (e.g., text input for string, checkbox for boolean, etc.). DisplayFor will do the same except that it will render non-editable markup. You can find more details about the display templates here. However, the true power of these methods can be seen when you create custom templates for object types. This is a more advanced topic but if you are interested in this, you can see this article for more details.

Now back to basics - how do we add a new View? In the folder structure above, you can see the Views folder and the subfolders called User, School, Shared, etc. Just right-click on the folder where you want to put the View, go to Add New View, and the following dialog will be shown to you:

Here you can enter the name of the View (usually it is the same as the name of the controller action) and the type of the Model object that will be shown. Also, you can add an empty View and start coding it, or you can select some of the predefined templates for list, details, edit, create, or delete.

You can imagine Views as separate pages that will be shown to the user. However, there are a few other types of Views (described below).

Layout page

When you are creating a set of pages, probably you will need to use the same elements on many pages. As an example, all pages will have the same menu, the same CSS/JavaScript files included etc. In ASP.NET MVC, you do not need to copy the same elements on each page. You can use the so-called layout pages where a general layout of the entire MVC application will be defined and used on each View page. An example of a layout page that will be used in this project is shown in the following listing:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>This is a title of the page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
    @RenderSection("PageScripts",false)
</head>

<body>
    @RenderBody()
</body>
</html>

As you can see, in the layout page, I have included all the necessary CSS/JavaScript files that will be used across all pages. Also, I have defined two custom placeholders where each View will put specific content. These two placeholders are:

  1. Section PageScripts - where each page will be able to put some JavaScript or CSS files that will be required only on that page.
  2. RenderBody statement that defines where the content of a particular View will be injected in the general layout.

Partial views

Another way to organize and reuse your View code is to put elements that are used on several Ciews into separate files. These are not standalone Views that are shown to the user - these are only partial views that are included on other main View pages.

Partial Views are HTML templates as regular Vviews. An example of a partial view that shows the current date is shown in the following listing:

_CurrentDateView.cshtml
<div class="now">Current date is @DateTime.Now.ToString()</div>

Whenever you need to include this partial view, you can just call it by name as shown in the following example:

@Html.Partial("_CurrentDateView")

In the place of the call, the entire content of the View will be included. You can put this statement in standard views, layout pages, and even in other partial views.

Controller

Controller is the heart of the processing logic in MVC model. When a URL is sent to an internet application in the format /<<Controller>>/<<Action>>/<<Parameter>> (e.g., /User/Details/1), it will be parsed and the class called <<Controller>>Controller (e.g., UserController) will be found, the method <<Action>> in that controller will be called (e.g., method Details in the above URL), and the parameter will be passed to that method. The Controller will perform all the necessary processing - it will find a Model and pass it to the View.

The Controller can have any public method with arbitrary parameters that will be passed. As an example, the following listing shows the Controller called ExampleController with a method ControllerAction that receives three parameters - id, name, and flag.

public ExampleController
{
        public ActionResult ControllerAction(int id, string name, bool flag)
    {
        var model = GetModel(id, name, flag);
        return View(model);
    }
}

You can call this Controller's action using the following URL:

/Example/ControllerAction?id=17&name=test&flag=true

This is the default mapping between URL routes and controller/actions where the first word in the URL represents a controller name, and the second one is the action method name. However, you can modify it and add your own routing mapping rules. You can see more details about the custom routing in the Creating custom routes article.

The Controller will automatically map parameters from the request to the method arguments by name. This is useful if you have a form with many parameters that can be automatically read from the request and the user in the action method body.

How you can add a new Controller? It is similar to adding new Views - go to the Controller folder, right-click, and add a new Controller. The following dialog will be shown:

Here you can enter the name of the Controller - note that it must be in the format <<Name>>Controller. Also, you can choose one of the predefined templates - empty controller, controller with list, details, edit, create, and delete actions, and controller that is already connected to the database via Entity Framework. In this example, I have started with an empty controller. Once you create an empty controller, you can add action methods in the following format:

public MyController{
    [Get]
    public ActionResult MyAction()
    {
        return View();
    }
}

The action method should return a view that will display the HTML in the browser (ActionResult type in the example above). By default if you add the MyAction method in the MyController class, it will be called when the /My/MyAction URL is sent. You can change this behavior, but it will not be described in this beginner level article. Also, you might notice the [Get] attribute that is placed before the method. This attribute tells the action that it should react only to a GET HTTP protocol. As an alternative, I could set [Post] instead of [Get] or I could leave it blank so the action would be opened on both GET and POST protocols.

Also, you must have noticed that the last statement in the action is return View(). If an action MyAction is placed in MyController, this statement will find the MyAction.cshtml View in the My folder in the Ciews section. This is the default rule for returning Views in action methods. If you do not want to use this default view, you can choose what View should be returned by specifying the View name, e.g.,

return View(name);

Note that you have an easy way to go to the View, or to add a View for a particular action. Just right click on the action and you will see a context menu that will enable you to add a View for this action. Add View action will open the "Add View" dialog as in the previous section. If a View with the same name as an action already exists, "Go to view" will open the view page.

jQuery

Although it is not a direct part of MVC, jQuery is a very useful JavaScript library that can enable you to enhance your user interface. The first useful thing you will be able to do is easily find HTML elements in the HTML. Some of the simplest queries are shown in the following table:

jQuery selector Description
$("table")Find all table nodes in the HTML
$("#Name")Find elements in the HTML with ID Name
$(".required")Find all elements in the HTML that have CSS class "required"
$("table a.delete") In any table, find all A tags that have CSS class "delete"
$("table tr:odd") Find all odd rows in the table

Once you find elements with jQuery selectors, you can hide them, change their color, attributes (classes, values, inner text), add some event handlers to them (click, double click), etc. An example of the code that attaches a click handler to the link is shown in the following listing:

$('a').click(function (event) {

    // prevent default action (going to the another page)
    event.preventDefault()

    // Do something
});

Also, jQuery contains a set of useful plug-ins that enable you to enhance your UI elements. Some examples are shown in the following table:

Plug-inDescription
$("input.calendar").datepicker() Add date picker (calendar) dialog on each input element that has CSS class "calendar"
$("form").validate() Add JavaScript validation on the form
$("table").dataTable()Add JavaScript sorting, pagination, and filtering in the table

You can fine more details and tutorials about jQuery on the jQuery documentation site. There is also an interesting article "jQuery for beginners" where you can find some interesting examples. This is optional, but very easy and useful to add in the MVC application. Note that when you create an MVC application, jQuery will be automatically included in the project. However, plug-ins are not part of core jQuery that is included in the MVC project so you will need to find them and put them in your project manually.

How can you use this JavaScript code? First, you will need to include the jQuery library from the jQuery download page. In your MVC project, you will probably find this library included in the scripts folder so you can just add a reference to this script in the layout page. Then you will be able to use this library - an example is shown in the following listing:

<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("table").fadeOut("slow");
    }
</script>

In this example, I have included jQuery version 1.7.1. and added a fade out effect on the table element. Note that this statement is placed in the document ready wrapper. Using this wrapper, any JavaScript code within it will be called when an entire document is loaded and ready to be processed. This is a common practice in jQuery programming. Here I have added jQuery code as an inline script, but you can put it into a separate file.

Creating your first MVC application

In this section, I will show how you can create a simple MVC application that lists, edits, creates, and deletes users.

List/Index page

On the list page will be displayed a table with a list of users in the repository. The page will be opened when the /User/Index URL is called. Therefore, we would need to create an Index method and place it in the UserController class. An example of the Index method is shown in the following listing:

public ActionResult Index()
{
    var model = UserRepository.Users;
    return View(model);
}

This method is fairly simple. It takes a list of users from the repository and passes it to the View. The list view takes this list and displays a table as shown in the following listing:

<table class="display">
    <thead>
    <tr>
        <th>
            Name
        </th>
        <th>
            Address
        </th>
        <th>
            Town
        </th>
        <th>
            County
        </th>
        <th>
            Rating
        </th>
        <th></th>
    </tr>
    </thead>
    <tbody>

@foreach (var item in Model) {
    <tr>
        <td>
            @item.Name
        </td>
        <td>
            @item.Address
        </td>
        <td>
            @item.Town
        </td>
        <td>
            @item.County
        </td>
        <td>
            @item.Rating
        </td>
        <td>
            <a href="/User/Details/@item.UserID">Details</a> |
            <a href="/User/Edit/@item.UserID">Edit</a> |
            <a href="/User/Delete/@item.UserID" class="delete">Delete</a>
        </td>
    </tr>
}
</tbody>
</table>

As you can see, this list view has taken a collection of user objects and outputs them as an HTML table in the foreach loop. Note that you do not need to create an HTML wrapper with head and body tags. These are defined in the layout page, and this part of the HTML code is just injected in the middle of the page (the RenderBody statement in the layout page above). An example of the list page is shown in the following figure:

Applying the jQuery DataTables plug-in

The table you saw is just a plain table without any functionality. However you can easily enhance this table with the jQuery JavaScript library to add some advanced features such as sorting, pagination, filtering, etc. In the layout page, you saw that I have put a PageScripts placeholder that allows each view to put some custom JavaScript or CSS. In this example, only on the list page, I will add some JavaScript that will enhance this table. An example of this additional script is shown in the following listing:

@section PageScripts{
    <link href="/Content/dataTable/demo_table.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery.dataTables.1.8.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("table").dataTable();
        }
    </script>
}

This script has included jQuery DataTables CSS and JavaScript files, and applied DataTables function on the HTML table. As a result, you will convert this plain table to a feature-rich table shown on the following figure:

I will not explain how this jQuery plug-in can be used in more detail, but if you are interested, you can take a look at the Enhancing HTML tables using the jQuery DataTables plug-in article.

Details page

On the details page will be shown information of a particular user by ID. The request that is sent to the server-side is in the following format:

/User/Details/123

In this request, you can see that UserController will be called, and that the Details method with parameter 123 will be executed. 123 is the ID of the record that will be shown. The Details method will take the ID of the user, find this user in the model repository, and pass it to the view:

public ActionResult Details(int id)
{
    var model = UserRepository.Users.First(user => user.UserID == id);
    return View(model);
}

The View is also simple - it receives the user model object and injects user properties into the view. Part of view is shown in the following listing:

@model JQueryMVC.Models.User

<h2>User Details</h2>
<fieldset>
    

Categories: MVC, ASP.NET, JQUERY

Post a Comment

Oops!

Oops, you forgot something.

Oops!

The words you entered did not match the given text. Please try again.

You must be a member to comment on this page. Sign In or Register

0 Comments