Overview of ASP.NET MVC Views and HTML Helpers

In ASP.NET web forms the request to an URL goes to a physical file on the web server. In ASP.NET MVC application the request to an URL does not represent a physical file, rather it invokes a method in a class (controller action). A controller action in an ASP.NET MVC application typically returns a View most of the times, however it can also perform other actions like returning a file or re-directing to another controller action.

A sample Controller action looks like below

http://serverurl/ControllerName/ActionName

http://serverurl/Home/Index

Home is the default controller that we will get when we create an ASP.NET MVC application in Visual Studio. Index is the default controller action that comes default in Visual Studio.

ASP.NET MVC framework works based on certain conventions. For every controller a sub-folder gets created under Views. For every controller action, a .cshtml file gets created under the respective sub-folder inside Views folder.

Now let’s move to understand HTMLHelpers. ASP.NET web forms have server controls which is used for data entry and UI form processing. In ASP.NET MVC we don’t have server controls, we need to rely on HTML Controls for data entry and UI form processing.

1. BeginForm

The BeginForm helper method denotes the start of an HTML form and it renders an HTML form element. The BeginForm method has 13 overrides and the i’m using the following  version of override in this post

   @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        { 
        
        }

2.RadioButton helper

The Radio button helper helps us to render a RadioButton control. It can be bounded to a model property, which also can be set with values and group for the RadioButton.

 Male @Html.RadioButtonFor(model => model.Sex,"Male")
                Female @Html.RadioButtonFor(model => model.Sex, "Female")

3.Textbox helper

The @Html.EditorFor helper supports us to render a TextBox control for data capture. It can be bound to a model property.

        @Html.EditorFor(model => model.Age)

4.DropDownListControl

The @Html.DropDownListfor helper control supports us to render a dropdownlist control. It can be databound to a IEnumerable>T> which needs to be type casted as SelectList, while performing data binding.

 @Html.DropDownListFor(model => model.PolicyType, ViewData["PolicyType"] as SelectList)

5.CheckBox Control

The @Html.CheckBox control support us to to render a CheckBox control. It can be data bound to a boolean property in the Model.

@Html.CheckBoxFor(model=>model.ReceiveMails)

6.Label Control

The @Html.Label control supports us to render a Label control, whose literal value is bound from a string property in the Model.

 @Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })

 

7. ActionLink Control

The @Html.ActionLink control supports us to link to an action method in a controller when the link is clicked.

  @Html.ActionLink("Back to List", "Index")

With the above briefing, i will be creating a View to capture the details for generating an InsuranceQuotation. The Model object definition looks like below :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCDemo2.Models
{
    public class InsurancePolicy

    {

        public string FirstName { get; set; }
        public string LastNane { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        
        public string PolicyType { get; set; }

        public int PolicyTerm { get; set; }
        public int SumAssured { get; set; }

        public bool ReceiveMails { get; set; }


    }
}

My end goal is to create a View (shown below) to capture the details for generating Quotation.

image

The definition of my View ‘GenerateQuote.cshmtl’ looks like below :-

@model MVCDemo2.Models.InsurancePolicy

@{
    ViewBag.Title = "GenerateQuote";
}

<h2>GenerateQuote</h2>



@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>InsurancePolicy</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastNane, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastNane)
                @Html.ValidationMessageFor(model => model.LastNane)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age)
                @Html.ValidationMessageFor(model => model.Age)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Sex, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                Male @Html.RadioButtonFor(model => model.Sex,"Male")
                Female @Html.RadioButtonFor(model => model.Sex, "Female")
                @Html.ValidationMessageFor(model => model.Sex)
            </div>
        </div>

        

        <div class="form-group">
            @Html.LabelFor(model => model.PolicyType, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.PolicyType, ViewData["PolicyType"] as SelectList)
                @Html.ValidationMessageFor(model => model.PolicyType)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PolicyTerm, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PolicyTerm)
                @Html.ValidationMessageFor(model => model.PolicyTerm)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SumAssured, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SumAssured)
                @Html.ValidationMessageFor(model => model.SumAssured)
            </div>
        </div>

        <div class="form-group">

            @Html.LabelFor(model=>model.ReceiveMails)
            @Html.CheckBoxFor(model=>model.ReceiveMails)
           
        </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

This completes this article. My next post on ASP.NET MVC is here.

 Subscribe to my blog

Various options of passing data from ASP.NET MVC Controller to View

In ASP.NET MVC framework, we have got various options for passing data from Controller to View. Some of the options that i know and used are listed below :-

1. Use a strongly typed model object

2. Use a dynamic type (using @model syntax)

3.Use a ViewBag

This article focuses on explaining the above three methods of passing data from Controller to View.  Let’s create a simple ASP.NET MVC application to demo this one. Since there is a Cricket world cup fever going now, i will be creating a sample MVC application to display list of countries.

I’m adding the below model to the project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; 

namespace MVCDemo1.Models
{
    public class Countries
    { 

        public String Name { get; set; }
        public string Group { get; set; }
        public string DressColor { get; set; }
        public int NoOfTropies { get; set; }
    }
} 

I’ll be creating a new controller by name Country to handle various types of views(strongly typed views, loosely typed views and views accessing viewbag objects directly for the model Countries.

In the CountryController.cs, i’m setting up the values for CountryCollection

List<Countries> oCountries = new List<Countries> { 
        new Countries{Name="India",NoOfTropies=2,Group="A",DressColor="Blue"},
        new Countries{Name="Australia",NoOfTropies=3,Group="B",DressColor="Yellow"},
        new Countries{Name="SouthAfrica",NoOfTropies=0,Group="C",DressColor="Purple"}

        };

1.Use a strongly typed model object to pass data from Controller to View

In this approach, I’m adding a Controller action by name ‘StrongView’ to return the View for ActionResult.

public ActionResult StrongView()
        {

            return View(oCountries);

        }

Right click on the controller action and Add a View by choosing the Model class, which makes it a Strongly typed view.

image

Run the Solution and the View with CRUD operations look like below.

image

At the top of the View, model is referenced strongly which makes it Strongly typed View.

@model IEnumerable<MVCDemo1.Models.Countries>

Now, let’s move to the approach #2.

 

2. Use a dynamic type (@model syntax) to pass data from Controller to View

Let’s add another controller action by name ‘LooseView’ for passing loosely typed objects from Controller to View.

 public ActionResult LooseView()
        {

            return View(oCountries);
        
        }

Right click on the Controller action, Add View and do not choose any model class, that will make it as dynamically typed.

image

At the top of the View add a reference to dynamically typed view and Grab the Model data from dynamic object.

@model dynamic
@{
    ViewBag.Title = "LooseView";
}

<h2>LooseView</h2>

@foreach(var oCountry in Model)
{
    @oCountry.Name;
}

image

Now let’s move to the approach #3.

3. Use ViewBag to pass the data from Controller to View

Now let’s add a Controller action by name ‘ThirdView’ which sets the Country Collection and returns the View.

  public ActionResult ThirdView()
        {
            ViewBag.Countries = oCountries;
            return View();

        }

Let’s add a View by name ‘ThirdView’

image

I’ll be fetching the Model object from ViewBag and rendering it in the View.

@{
    ViewBag.Title = "ThirdView";
}

<h2>ThirdView</h2>

@foreach (var oCountry in ViewBag.Countries)
{
    @oCountry.Name;
}

image

 Subscribe to my blog