MVC :: Understanding Views, View Data, and HTML Helpers

Similar documents
MVC :: Understanding Models, Views, and Controllers

MVC :: Preventing JavaScript Injection Attacks. What is a JavaScript Injection Attack?

MVC :: Understanding Controllers, Controller Actions, and Action Results

When you create a new ASP.NET MVC application, the application is already configured to use URL Routing. URL Routing is setup in two places.

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied ASP.NET MVC USING C#

Working with Controllers

Introducing Models. Data model: represent classes that iteract with a database. Data models are set of

Justin Jones 21 st February 2013 Version 1.1 Setting up an MVC4 Multi-Tenant Site

ASP.NET MVC 3 Using C# Rev. 3.0

INTRO TO ASP.NET MVC JAY HARRIS.NET DEVELOPER

Using Visual Studio 2017

Babu Madhav Institute of information technology 2016

blink.html 1/1 lectures/6/src/ form.html 1/1 lectures/6/src/

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to

Pro ASP.NET MVC 2 Framework

HTML 5 Form Processing

ASP.NET MVC 4 Using C# Evaluation Copy. Student Guide Revision 4.5. Object Innovations Course 4143

Description: This feature will enable user to send messages from website to phone number.

How browsers talk to servers. What does this do?

Professional ASP.NET MVC 4

Course Outline. Developing Web Applications with ASP.Net MVC 5. Course Description: Pre-requisites: Course Content:

Developing Ajax Applications using EWD and Python. Tutorial: Part 2

NerdDinner Step 1: File->New Project

Lab 10: Application Architecture Topics

Implementing a chat button on TECHNICAL PAPER

20486-Developing ASP.NET MVC 4 Web Applications

5 Years Integrated M.Sc. (IT) 6th Semester Web Development using ASP.NET MVC Practical List 2016

home.php 1/1 lectures/6/src/ include.php 1/1 lectures/6/src/

ASP.NET Security. 7/26/2017 EC512 Prof. Skinner 1

MVC CRUD. Tables: 1) Dinners (First Table)

Introduction to Web Development

this is a cat CS50 Quiz 1 Review

web.py Tutorial Tom Kelliher, CS 317 This tutorial is the tutorial from the web.py web site, with a few revisions for our local environment.

ASP.NET MVC Music Store Tutorial

ABSOLUTE FORM PROCESSOR ADMINISTRATION OPTIONS

Course Topics. The Three-Tier Architecture. Example 1: Airline reservations. IT360: Applied Database Systems. Introduction to PHP

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Laravel

Naresh Information Technologies

Web Development and HTML. Shan-Hung Wu CS, NTHU

CIS 3308 Logon Homework

Developing ASP.NET MVC 5 Web Applications

Syncfusion Report Platform. Version - v Release Date - March 22, 2017

IN PRACTICE. Daniele Bochicchio Stefano Mostarda Marco De Sanctis. Includes 106 practical techniques MANNING

HTML. HTML Evolution

Bruce Moore Fall 99 Internship September 23, 1999 Supervised by Dr. John P.

What You Need to Use this Book

Should you encounter any issues or have questions as you go through this registration process, please send an to:

JavaScript!= Java. Intro to JavaScript. What is JavaScript? Intro to JavaScript 4/17/2013 INTRODUCTION TO WEB DEVELOPMENT AND HTML

LAMPIRAN. Universitas Sumatera Utara

IN ACTION. Jeffrey Palermo Jimmy Bogard Eric Hexter Matthew Hinze Jeremy Skinner. Phil Haack. Third edition of ASP.NET MVC in Action FOREWORD BY

E-Commerce Web Application

JavaScript CSCI 201 Principles of Software Development

Spring 2014 Interim. HTML forms

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer ASP.NET WP

Table of contents. DMXzoneUniformManual DMXzone

ASP NET MVC TASK TUTORIAL OWNERS MANUAL

CMT111-01/M1: HTML & Dreamweaver. Creating an HTML Document

LINQ as Language Extensions

Produced by. Web Development. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

How to Set Up a Custom Challenge Page for Authentication

Design and Implementation of File Sharing Server

Form Processing in PHP

A QUICK GUIDE TO PROGRAMMING FOR THE WEB. ssh (then type your UBIT password when prompted)

SportsStore: Administration

Web Security IV: Cross-Site Attacks

Index. Bower, 133, 352 bower.json file, 376 Bundling files, 157

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "

Dreamweaver: Portfolio Site

Web Forms for Marketers 8.0 Rev: September 13, Web Forms for Marketers 8.0

Module 46 (XSS and Browser Exploitation)

Accessibility of EPiServer s Sample Templates

DB2 Web Query (REST based) Application Extension. Usage Instructions

CSE 143: Computer Programming II Spring 2015 HW2: HTMLManager (due Thursday, April 16, :30pm)

Overview... 7 Tabs... 8 Selected Tables... 8 Load Tables Button Selected Views... 8 Load Views Button Clear Selection Button...

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

User Guide for Direct Post Method JavaScript Relay URL Redirect

IBM Security Access Manager What s in the box : InfoMap Authentication Mechanism IBM SECURITY SUPPORT OPEN MIC. 13 Dec 2017

Number: Passing Score: 800 Time Limit: 120 min File Version: 1.0. Demo

AngularJS Intro Homework

Kentico CMS User s Guide 4.1

Introduction to HTML5

Action-packed controllers

Payment Pages Customisation Version 2

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 13: Intro to JavaScript - Spring 2011

Technical Guide Login Page Customization

Lecture 9. Forms & APIs 1 / 38


Course Topics. IT360: Applied Database Systems. Introduction to PHP

Hyperlinks, Tables, Forms and Frameworks

Quick.JS Documentation

CHAPTER 2 Understanding URL Routing

Getting Started with Moodle 2.0

Writing Perl Programs using Control Structures Worked Examples

John Coggeshall Copyright 2006, Zend Technologies Inc.

Summary. 1. Page 2. Methods 3. Helloworld 4. Translation 5. Layout a. Object b. Table 6. Template 7. Links. Helloworld. Translation Layout.

User Guide for Direct Post Method Direct Redirect

LAMPIRAN. 1. Source Code Data Buku. using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.

HTML5 a clear & present danger

Hyper- Any time any where go to any web pages. Text- Simple Text. Markup- What will you do

Psychology Experiments on the Web Using PHP and MySQL

Transcription:

MVC :: Understanding Views, View Data, and HTML Helpers The purpose of this tutorial is to provide you with a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. By the end of this tutorial, you should understand how to create new views, pass data from a controller to a view, and use HTML Helpers to generate content in a view. Understanding Views Unlike ASP.NET or Active Server Pages, ASP.NET MVC does not include anything that directly corresponds to a page. In an ASP.NET MVC application, there is not a page on disk that corresponds to the path in the URL that you type into the address bar of your browser. The closest thing to a page in an ASP.NET MVC application is something called a view. In an ASP.NET MVC application, incoming browser requests are mapped to controller actions. A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action. Listing 1 contains a simple controller named the HomeController. The HomeController exposes two controller actions named Index() and Details(). Listing 1 HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Controllers [HandleError] public class HomeController : Controller public ActionResult Index() return View();

public ActionResult Details() return RedirectToAction("Index"); You can invoke the first action, the Index() action, by typing the following URL into your browser address bar: /Home/Index You can invoke the second action, the Details() action, by typing this address into your browser: /Home/Details The Index() action returns a view. Most actions that you create will return views. However, an action can return other types of action results. For example, the Details() action returns a RedirectToActionResult that redirects incoming request to the Index() action. The Index() action contains the following single line of code: return View(); This line of code returns a view that must be located at the following path on your web server: \Views\Home\Index.aspx The path to the view is inferred from the name of the controller and the name of the controller action. If you prefer, you can be explicit about the view. The following line of code returns a view named Fred : return View( Fred ); When this line of code is executed, a view is returned from the following path: \Views\Home\Fred.aspx Creating a View You create a view by right-clicking a folder in the Solution Explorer window and selecting the menu option Add, New Item (see Figure 1). Select the MVC View Page template to add a standard view to your project.

Figure 1 Adding a new view to a project Realize that you can t add views willy-nilly to a project like you can add pages in an ASP.NET or Active Server Pages application. You must add a view to a folder that has the same name (without the Controller suffix) as a controller. For example, if you want to create a new view named Index that can be returned by a controller named ProductController, then you must add the view to the following folder in your project: \Views\Product\Index.aspx The name of the folder that contains a view must correspond to the name of the controller that returns the view. Adding Content to a View A view is a standard (X)HTML document that can contain scripts. You use scripts to add dynamic content to a view. For example, the view in Listing 2 displays the current date and time. Listing 2 \Views\Home\Index.aspx CodeBehind="Index.aspx.cs" Inherits="MvcApp.Views.Home.Index" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<title>index</title> The current date and time is: <% Response.Write(DateTime.Now);%> </div> Notice that the body of the HTML page in Listing 2 contains the following script: <% Response.Write(DateTime.Now);%> You use the script delimiters <% and %> to mark the beginning and end of a script. This script is written in C#. It displays the current date and time by calling the Response.Write() method to render content to the browser. The script delimiters <% and %> can be used to execute one or more statements. Since you call Response.Write() so often, Microsoft provides you with a shortcut for calling the Response.Write() method. The view in Listing 3 uses the delimiters <%= and %> as a shortcut for calling Response.Write(). Listing 3 Views\Home\Index2.aspx CodeBehind="Index2.aspx.cs" Inherits="MvcApp.Views.Home.Index2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <title>index2</title> The current date and time is: <%=DateTime.Now%>

</div> You can use any.net language to generate dynamic content in a view. Normally, you ll use either Visual Basic.NET or C# to write your controllers and views. Using HTML Helpers to Generate View Content To make it easier to add content to a view, you can take advantage of something called an HTML Helper. An HTML Helper is a method that generates a string. You can use HTML Helpers to generate standard HTML elements such as textboxes, links, dropdown lists, and list boxes. For example, the view in Listing 4 takes advantage of two HTML Helpers, the TextBox() and Password() helpers, to generate a Login form (see Figure 2). Listing 4 -- \Views\Home\Index3.aspx CodeBehind="Index3.aspx.cs" Inherits="MvcApp.Views.Home.Index3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <title>login Form</title> <form method="post" action="/home/login"> <label for="username">user Name:</label> <br /> <%=Html.TextBox("userName")%> <br /><br />

<label for="password">password:</label> <br /> <%=Html.Password("password")%> <br /><br /> <input type="submit" value="log In" /> </form> </div> Figure 2 A standard Login form All of the HTML Helpers methods are called on the Html property of the view. For example, you render a TextBox by calling the Html.TextBox() method. Notice that you must use the script delimiters <%= and %> when calling an HTML Helper. An HTML Helper simply returns a string. You need to call Response.Write() in order to render the string to the browser.

Using HTML Helper methods is optional. They make your life easier by reducing the amount of HTML and script that you need to write. The view in Listing 5 renders the exact same form as the view in Listing 4 without using HTML Helpers. Listing 5 -- \Views\Home\Index4.aspx CodeBehind="Index4.aspx.cs" Inherits="MvcApp.Views.Home.Index4" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <title>login Form without Help</title> <form method="post" action="/home/login"> <label for="username">user Name:</label> <br /> <input name="username" /> <br /><br /> <label for="password">password:</label> <br /> <input name="password" type="password" /> <br /><br /> <input type="submit" value="log In" /> </form> </div>

You also have the option of creating your own HTML Helpers. For example, you can create a GridView() helper method that displays a set of database records in an HTML table automatically. We explore this topic in the tutorial Creating Custom HTML Helpers. Using View Data to Pass Data to a View You use another property of a view, the ViewData property, to pass data from a controller to a view. For example, the controller in Listing 6 adds a message to view data. Listing 6 ProductController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Controllers public class ProductController : Controller public ActionResult Details() ViewData["message"] = "Hello World!"; return View(); The controller ViewData property represents a collection of name and value pairs. In Listing 6, the Details() method adds an item to the view data collection named message with the value Hello World!. When the view is returned by the Details() method, the view data is passed to the view automatically. The view in Listing 7 retrieves the message from the view data and renders the message to the browser. Listing 7 -- \Views\Product\Details.aspx CodeBehind="Details.aspx.cs" Inherits="MvcApp.Views.Product.Details" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <title>product Details</title> <%=Html.Encode(ViewData["message"])%> </div> Notice that the view takes advantage of the Html.Encode() HTML Helper method when rendering the message. The Html.Encode() HTML Helper encodes special characters such as < and > into characters that are safe to display in a web page. Whenever you render content that a user submits to a website, you should encode the content to prevent JavaScript injection attacks. (Because we created the message ourselves in the ProductController, we don t really need to encode the message. However, it is a good habit to always call the Html.Encode() method when displaying content retrieved from view data within a view.) In Listing 7, we took advantage of view data to pass a simple string message from a controller to a view. You also can use view data to pass other types of data, such as a collection of database records, from a controller to a view. For example, if you want to display the contents of the Products database table in a view, then you would pass the collection of database records in view data. You also have the option of passing strongly typed view data from a controller to a view. We explore this topic in the tutorial Understanding Strongly Typed View Data and Views. Summary This tutorial provided a brief introduction to ASP.NET MVC views, view data, and HTML Helpers. In the first section, you learned how to add new views to your project. You learned that you must add a view to the right folder in order to call it from a particular controller. Next, we discussed the topic of HTML Helpers. You learned how HTML Helpers enable you to easily generate standard HTML content. Finally, you learned how to take advantage of view data to pass data from a controller to a view.