Friday, February 8, 2013

View


ASP.Net MVC View is the fourth post in a series of tutorials which introduces the basics of ASP.Net MVC programming.

Previous Posts:
MVC Introduction
HTML Forms
Model

Views


IN MVC, Views are what we see and interact with. The view can be a web page on a desktop, tablet or mobile device. The view can also be an app or a console application or any number of options for interacting with an application. ASP.Net MVC controllers supports the concept of returning views which are web pages, but controllers can also return JSON, XML and many other formats which can be consumed by numerous devices. In fact a request to a server can return the same data which can be shown differently depending on the device. The server is not very concerned about what device consumes the data, it just knows a request has been made and data must be processed and return in a particular format. This concept is termed 'separation of concerns' and is a powerful concept that differentiates ASP.Net forms from ASP.Net MVC.

Mobile and tablet devices are becoming more popular than desktop and notebooks and while this has been primarily consumer led until now, this progression is started to take hold in business. Developing separate applications for different devices is a luxury that is difficult to justify for most businesses. There are ways and means to optimise and reduce the server side code but the connection between the user interface and business logic is problematic. MVC has come at a good time for web and mobile based applications.

Razor

As per my Model tutorial, I will be programming in C#. I will also be using Razor as the syntax in the ASP.Net web page. Razor is almost identical to C# if you are using C# for your project and is the code that will be inter-dispersed with your HTML syntax. Razor is relatively new and was introduced with MVC 3. Prior to that a similar syntax was used to that in ASP.Net forms which used <%= %> to distinguish ASP.Net code from HTML. Razor uses an @ symbol which is far easier to read. If you are starting out, I would suggest using Razor otherwise use what ever you are comfortable with. Note - although ASP.Net code is inter-dispersed with HTML which cannot be avoided, I tend to use it cautiously and avoid or minimise placing business logic in the View.

The View

There will be a little more explanation when I get to Controllers but for now think of a view as a web page. In C#, the web page will have an extension of cshtml and in VB.Net it will be vbhtml. The web server will do the necessary processing to convert these files to HTML.

Strongly typed views

MVC3 introduced the concept of strongly typed views. Basically this means each web form is strongly associated with one object e.g. Person, Car, Project. One object = one form. You can have more than one form on a web page in MVC but this can be a little head wrecking in the beginning as there is a tendency to be loose with the data that is retrieved and stored to and from a server. For example if you are working with a SQL database, you can query data for a web page based on joins on many tables and now MVC is restricting you to only one object which is associated with one table in a SQL database. But don't worry, there are techniques to overcome this restriction. You can workaround the strongly typed view concept by using dynamic types but it doesn't make for great coding and you loose the IntelliSense in Visual Studio. I stick to strongly typed views where ever possible as it is a self organising process which produces better outputs.

Standard folders and files

Following the convention over configuration theme, MVC expects certain files and folders to be in the right place. This convention provides great familiarity across projects.

In the Solution Explorer, expand the Views folder. Note the View folder is a standard MVC folder. There will be a number of standard folders and views within the views folder which were generated based on a template.
The Account folder contains views used for logging on to your site. I will cover this in detail on a separate post.
The Shared folder is a standard MVC folder that contains views that are accessible universally. MVC does its best to find an explicitly defined view. If it cannot find it, it will look in the Shared folder. The shared folder is commonly used for templates and common views that occur throughout a web application e.g. advert, the latest news or an error page.
The Home folder is akin to the root folder of a conventional website. The Index file for the website resides here and optionally other files can also. The bulk on the view for a website can be located in the Home folder which is not uncommon for a small web site. Larger sites will contain more folders organised based on object names. ASP.Net MVC does a little bit of MVC magic to route requests from the root index file to the home index file e.g. http://acme/ gets mapped to http://acme/home/index.


In the root of the Views folder is a special partial view named _ViewStart.cshtml. This partial view is used for all views in the Views folder. If you open the file, you will notice one line of code which defines the layout as referencing "~/Views/Shared/_Layout.cshtml". This is basically saying that all views should use _Layout.cshtml in the ~/Views/Shared/ folder for the Layout. A layout is akin to a template.
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Partial Views are prefixed with an underscore e.g. _Layout.cshtml. Partial Views are subsets of Views and are not used to display a web page but can be used to display part of a web page. In the case of the template, they are often used to display the header, menus, footer and so on that are common to all views.

  1. We are going to create a view to allow a person to be created. First create a folder named People under views. Note, the plural is used. Again this is convention.
  2. Then create a View named Create by right clicking on the Person folder, selecting Add and then selecting view.
  3. Select Razor (CSHTML) as the View Engine. Note, you can use a combination of Razor and ASPX (C#) but not in the same view. If you are new to MVC, then select Razor.
  4. Select Create a strongly-typed view. From the Model class pull down list, select Person (Acme.Intranet.Models). This is the class we created in the Model post.
  5. Select Edit from the list of Scaffold templates.
  6. Leave the text box for the layout or master page empty. We are going to use the layout defined in the _ViewStart.cshtml file.





If you used the settings in the form above, you should have the following code. Notice the @ symbol and the @ { } symbols. Razor uses the @ symbol to distinguish C# code from HTML code. @ { } is used to define a block or numerous lines of C# code.

@model Acme.Intranet.Models.Person

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Height)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Height)
            @Html.ValidationMessageFor(model => model.Height)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


MVC used Scaffolding to automatically generate the above code. Scaffolding was popularised by Ruby on Rails and is very useful for generating common code that occurs in CRUD (Create, Read, Update, Delete) operations.

At the top, the strongly typed view is defined by the @model statement. @model Acme.Intranet.Models.Person basically says that this form is is strongly typed to the Person object.

ViewBag is like a super variable that was introduced in MVC 3. Prior to MVC 3 ViewData was used. If you are new to MVC, you can ignore ViewData for now as they are used for similar functions. ViewBag can contain just about anything you want it to. It can store an object, a collection of objects, a simple string or integer or an array. ViewBag goes against the principals of MVC so a little care needs to be taken when using it. I will expand of ViewBag in the Controllers post.

Notice that many of the Razor code lines start with @Html. MVC contains items called Html helpers which are a set of defined functions that automate the generation of HTML code. Unlike ASP.Net forms, in MVC the automation is at a more granular level and importantly can be overridden or extended.


@Html.BeginForm() - This will output standard HTML for a form.
@Html.LabelFor - This will create static text for a label.
@Html.EditorFor - MVC will output the best html form element i.e. Input type="text" for strings such as Firstname
@Html.ValidationSummary - Displays a message if the form field is incomplete or has an invalid input. I will cover this in detail in a separate post.

The form contains a standard HTML submit button.

Outside the form, at the bottom of the view is a simple Html.ActionLink helper. This will create a hyperlink to another view, one named Index in this case. Html.ActionLink will be covered in a separate post but for now you can create simple links to other views using Html.ActionLink providing two parameters, the first being the text to display in the hyperlink and the second being the View name. @Html.ActionLink("Edit Employee", "Edit")


Concepts covered

  1. Seperation of Concerns
  2. Razor
  3. Strongly Typed Views
  4. Standard MVC View folders
  5. Partial Views
  6. _ViewStart.cshtml file
  7. Scaffolding
  8. CRUD (Create, Read, Update and Delete)
  9. Html Helpers
  10. ViewBag
Although our view is quite simple, it is sufficient for us to present a View that will create a Person. We still need a Controller to complete the MVC pattern for it all to work. The next post will introduce Controllers.


4 comments:

  1. thanks for shared wonderful information of giving best information.its more useful and more helpful. great doing keep sharing
    PHP Training in Chennai Adyar

    ReplyDelete
  2. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Regards,

    PHP Training in Chennai | Webdesigning Training in Chennai

    ReplyDelete

  3. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information.
    Regards,'
    Performance Tuning Training in Chennai | Oracle PL/SQL Training in Chennai

    ReplyDelete