04 Views
04 Views
MIS 324
Professor Sandvig
Outline
MVC Views
– Role
– HTML Helpers
– Razor
Role
Views provide user interface
– Displays information
– Collect data
Via Forms
Location
Views folder
Subfolder for each
controller
.cshtml file for each view
Location
Default:
– View name matches action method
Example:
– Controller name: dice
– Action method: index public ActionResult Index()
{
– Calls: Return View();
}
Views/dice/index.cshtml
Razor Syntax
.NET MVC Views support Razor Syntax
Razor: mixes html & C#
– Extension: .cshtml
Razor prefixed with @
Example:
<h2>@DateTime.Now.ToShortDateString()</h2>
Razor Syntax
Multi-statement code block
Use @{ …. }
Example:
@{
string date = DateTime.Now. ToLongDateString();
string greeting = "Hello!";
}
<h3>@greeting! Today is @date </h3>
Razor Syntax
Supports C#
control structures
– If
– If else
– For loops
– Etc.
Example:
@for (int i = 0; i < 10; i++)
{
<h3>@i. Go Vikings!</h3>
}
Razor Syntax
Display model values:
HTML Helpers
• Generate HTML in view
• Textboxes
• Dropdown lists
• Validation messages
• Labels
• etc.
HTML Helpers
Benefits:
• Two-directional:
• Display data from controller
• Pass user inputs to controller
• Validation
• Strongly typed data to model
HTML Helpers
HTML helper created by VS:
@Html.EditorFor(model => model.Name)
HTML:
<input class="text-box single-line" data-val="true" data-val-
required="The Name field is required." id="Name"
name="Name" type="text" value="Apollo" />
HTML Helpers
VS examines model and generates view
Contains form elements:
– Form tag
– Controls for user input
– Validation controls
– Labels
– Layout (using Bootstrap CSS framework)
HTML Helpers
Example 2 - checkbox
HTML helper:
– @Html.EditorFor(model => model.IsSeaHawkFan)
SeaHawks Fan?
HTML
– <input checked="checked" class="check-box" data-val="true" data-
val-required="The Seahawk Fan? field is required."
id="IsSeaHawkFan" name="IsSeaHawkFan" type="checkbox"
value="true" /> SeaHawks Fan?
Browser view
HTML Helpers
May need to edit default view
– Add options for dropdown lists and radio
buttons
– Modify formatting
– Relatively easy
Example: BigWebForm
Views Summary
Views provide user interface
– Display data
– Collect user information
Razor syntax
– Mix of C# and html
HTML Helpers
– Display data from model
– Two-directional
– Strongly typed
– Validation