MVC View

How to add a new View

  1. Right-click on the respective View folder under the "Views" directory

  2. Choose "Add" > "View..."

  3. Select "MVC 5 View" and click "Add"

  4. Type in the name of the View file you wish to add and click "Add"

Every View needs to be linked to a Model. Because of this, the first line of every View file is "@model" followed by the path leading to the corresponding Model class, for example like this:

@model Advantech.Ctos.Business.GroupName.ModelName

"GroupName" refers to the name of the directory that usually is the same as the first part of the Controller name.

If the View refers to a class within a Model class, you can simply add it using another dot operator like this:

@model Advantech.Ctos.Business.GroupName.ModelName.SubClass

General Structure of a View file

A View file is divided into 2 sections: the Content section (containing the <div> tags, etc) and the Script section (containing the JavaScript functions).

The Content section should only work if the Model is not null, so it needs to be encapsulated by the following:

@if (Model != null)
{
    ...
}

The Script section is located outside of this if-statement and is identified by the following tag:

<script type="text/javascript">
    ...
</script>

So, in total, the general structure of a View file looks like this:

@model Advantech.Ctos.Business.Example.ExampleMaster

@if (Model != null)
{
    ...
}

<script type="text/javascript">
    ...
</script>

Content section

The Content section of a View file is usually structured according to the tags described in the article "Custom CSS". So the Content section of a typical View file looks like this:

    <div class="content-title">Page Title</div>
    <div class="content-action">
        <a id="btn-1" class="btn btn-primary"> Button 1</a>
        ...
    </div>
    <div class="content-body">
        ...
    </div>

Script section

The Script section of a View file implements the different functionalities of the elements in the Content section.

Here, one needs to distinguish the function based on the point in time it should be executed.

If the function can already be executed from the start, nothing needs to be done.

If the function should only be executed when the Document Object Model ("DOM" or "document") is ready, i.e. the HTML Structure that is defined in the Content section of the View file, then it should be encapsulated in the following:

$(document).ready(function () {
    ...
});

If the function should only be executed when the entire page (including images, etc) is ready, then it should be encapsulated in the following:

$(window).ready(function () {
    ...
});

Functions that should be executed at the same point in time do not need to be encapsulated one by one but can all be placed within the same "$(document).ready" or "$(window).ready" function.

Implementation of different View Elements

Tables

Tables in a View file serve the purpose of displaying records of data (usually from a Data Repository or a List). A typical Table in our applications looks like this:

Tables are implemented using the <table> tag. The opening tag should contain an id (usually starting with "tbl" followed by the name of the Table) as well as the classes "display" (to adopt the standard design for Tables in the application) and "w-100" (for 100% width, i.e. using all of the space).

The <table> tags need to contain a <thead> tag (representing the Table Header) and a <tbody> tag (representing the Table Body).

In-between the <thead> tags, there is a <tr> tag (Row) that contains a <th> tag (Header) for every Column the Table should have. There, the Name of the respective Column is specified.

In-between the <tbody> tags, a <tr> tag (Row) should be created for each record in the Repository or List that should be displayed in the table. For this purpose, a foreach loop is used that iterates through the corresponding List by accessing it through the linked Model. Which data should be taken and to which column it should be mapped is specified within the <tr> tag using <td> tags. There, the corresponding Property is specified using the iterating variable of the loop, and the order in which they are implemented should match the order of the Column Headers. Consequently, the number of <td> tags should match the number of <th> tags.

Overall, a typical Table would be implemented like this:

<table id="tblName" class="display w-100">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            ...
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.List)
        {
            <tr>
                <td>@item.Data1</td>
                <td>@item.Data2</td>
                <td>@item.Data3</td>
                ...
            </tr>
        }
    </tbody>
</table>

For centering a Column Header or a Value in a Row, you can use the "text-center" class within the opening <th> or <td> tag, like this:

<th class="text-center"> XXX</td>

Forms

Forms in a View file serve the purpose of enabling the user to enter input data. A typical Form in our applications looks like this:

Similar to Tables, Forms are also done with <table> tags. However, this table is not made up of a head and a body part. It is made up of several rows (<tr>) that each have a Label and a Control Input (both encapsulated by <td> tags).

<table class="w-100">
    <tr>
        <td>Label 1</td>
        <td>Control Input 1</td>
    </tr>
    <tr>
        <td>Label 2</td>
        <td>Control Input 2</td>    
    </tr>
    ...
</table>

Labels are styled using the "field" classes (see article "Custom CSS"). So for example, a Label that has a width of 150px would be implemented like this:

<td class="field150">LabelName</td>

Control Inputs are styled using "text" classes (see article "Custom CSS"), so a Control Input of 100% width is implemented using the "text100" class. There are different types of Control Inputs that are implemented by using a corresponding HTML Helper:

Text Box

The simplest Control Input is a Text Box where the User can type in the input.

<td>@Html.TextBoxFor(mdl => mdl.XXX, new { @class = "text100" })</td>

Text Area

Text Areas are Text Boxes that are bigger and are used for longer texts, such as descriptions:

<td>@Html.TextAreaFor(mdl => mdl.XXX, new { @class = "text100" })</td>

Check Box

Check Boxes can only be used for boolean Properties:

@Html.CheckBoxFor(mdl => mdl.XXX)
<td>@Html.DropDownListFor(mdl => mdl.XXX, Converter.ToMvcList(Model.XXX), new { @class = "text100" })</td>

Submission Form

Usually, Forms serve the purpose of creating a new record in the database or to update an existing one, i.e. the inputs inserted by the User through the Form should be sent to the Server for further processing. To enable this functionality, the Form needs to be encapsulated by the following:

@using (Ajax.BeginForm("ActionName", "ControllerName", null,
    new AjaxOptions()
    {
        HttpMethod = "POST",
        OnBegin = "onXXXBegin",
        OnSuccess = "onXXXSuccess"
    }, new { @id = "formXXX" }))
{
    ...
}

The method "Ajax.BeginForm" requires 5 parameters:

  1. The first parameter requires the name of the Action that handles this Create/Update request

  2. The second parameter requires the name of the Controller in which the Action is located

  3. The third parameter is reserved for an object that contains route values (this parameter is usually set to "null")

  4. The fourth parameter is new instance of "AjaxOptions" that requires 3 Properties, which are "HttpMethod" (set to "POST" because lot of data is being sent to the Server), "OnBegin" (set to the name of the method in the Script section of the View file that handles the beginning of the submission process) and "OnSuccess" (set to the name of the method that handles the successful submission of the Form, also defined in the Script section)

  5. The fifth parameter is reserved for HTML Attributes, the most important use being for the id of the Form for later references

Identifiers

The different elements can be referred to by using identifiers. Any identifier is referred to by using "$("...")" but depending on the identifier, a different symbol is used. In the following, the different identifiers and their corresponding symbol are presented.

id

The most specific way to identify an element is by using the "id" class inside the opening tag like this:

<div id="someId"> ... </div>

For forms, the id is specified the following way:

@Html.TextBox(mdl => mdl.XXX, new { @id = "someId" })

If you want to refer to an element by its id, you use the "#" symbol, like this:

$("#btn-update")

class

If you want to refer to more than one element at the same time, e.g. because you want them to have the same functionality, you use a class, for example like this:

<div class="someClass"> ... </div>

For forms, classes are specified the following way:

@Html.TextBox(mdl => mdl.XXX, new { @class = "someClass" })

Classes are referred to by using the "." symbol, like this:

$(".someClass")

data-attr, data-id, etc

Finally, there is the possibility to refer to specific values that are contained in an element. This is especially used for rows in a table that are populated with data from the database. Each have a different value, so you want to refer to a specific one, but you cannot refer to it in advance because its existence depends on the population process. For this purpose, you can define an own attribute like "id" and "class" giving it an own customized name. Usually, we use the names "data-attr" or "data-id" in our applications, so it would look like this:

<tbody>
    @foreach (var item in Model.List)
    {
        <tr data-id="@item.ID" data-attr="@item.Value">
            <td>@item.Data1</td>
            ...
        </tr>
    }
</tbody>

Note that the values assigned to "data-id" and "data-attr" are not arbitrary names but the corresponding properties of the variable used to iterate through the records to populate the table.

Also note that a tag can have multiple identifiers. It can have an id, several classes and several custom attributes at once.

Implementation of different Functionalities

The following functions can be applied on any of the above mentioned identifiers.

Value

To use the value of a specific element, you use the following function:

$("#someId").val();

This is especially used for inputting values as parameters.

Click Event

To implement a functionality that should be executed when the element is clicked, you use the following function:

$("#someId").click(function () {
    ...
});

$("#someId").dblclick(function () {
    ...
});

$("#someId").on("click", function () {
    ...
});

Within the curly brackets, basic functions, such as "alert()", can be used as well as functions from the Custom Script.

Enter Event

$("#someId").onEnter(function () {
        ...
});
$("#someId").change(function () {
    ...
});

Last updated