SlideShare a Scribd company logo
1 of 13
Adding a View (C#)
  Tutorials

By Rick Anderson|January 12, 2011

In this section you're going to modify the HelloWorldController class to use view template files to
cleanly encapsulate the process of generating HTML responses to a client.
You'll create a view template file using the new Razor view engine introduced with ASP.NET MVC 3. Razor-
based view templates have a .cshtml file extension, and provide an elegant way to create HTML output
using C#. Razor minimizes the number of characters and keystrokes required when writing a view
template, and enables a fast, fluid coding workflow.
Start by using a view template with the Index method in the HelloWorldController class. Currently
the Indexmethod returns a string with a message that is hard-coded in the controller class. Change
the Index method to return a View object, as shown in the following:
publicActionResultIndex()
{
    returnView();
}
This code uses a view template to generate an HTML response to the browser. In the project, add a view
template that you can use with the Index method. To do this, right-click inside the Index method and
click Add View.




The Add View dialog box appears. Leave the defaults the way they are and click the Add button:
The MvcMovieViewsHelloWorld folder and the MvcMovieViewsHelloWorldIndex.cshtml file are created.
You can see them in Solution Explorer:
The following shows the Index.cshtml file that was created:
Add some HTML under the <h2> tag. The modified MvcMovieViewsHelloWorldIndex.cshtml file is shown
below.
@{
     ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>
Run the application and browse to the HelloWorld controller (http://localhost:xxxx/HelloWorld).
The Index method in your controller didn't do much work; it simply ran the statement return View(),
which specified that the method should use a view template file to render a response to the browser.
Because you didn't explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to
using the Index.cshtml view file in the ViewsHelloWorldfolder. The image below shows the string hard-
coded in the view.




Looks pretty good. However, notice that the browser's title bar says "Index" and the big title on the page
says "My MVC Application." Let's change those.


Changing Views and Layout Pages
First, you want to change the "My MVC Application" title at the top of the page. That text is common to
every page. It actually is implemented in only one place in the project, even though it appears on every
page in the application. Go to the /Views/Shared folder in Solution Explorer and open
the _Layout.cshtml file. This file is called a layout pageand it's the shared "shell" that all other pages use.
Layout templates allow you to specify the HTML container layout of your site in one place and then apply
it across multiple pages in your site. Note the @RenderBody() line near the bottom of the
file. RenderBody is a placeholder where all the view-specific pages you create show up, "wrapped" in the
layout page. Change the title heading in the layout template from "My MVC Application" to "MVC Movie
App".
<divid="title">
      <h1>MVC Movie App</h1>
  </div>
Run the application and notice that it now says "MVC Movie App". Click the About link, and you see how
that page shows "MVC Movie App", too. We were able to make the change once in the layout template
and have all pages on the site reflect the new title.




The complete _Layout.cshtml file is shown below:
<!DOCTYPE html>
<html>
<head>
    <metacharset="utf-8"/>
    <title>@ViewBag.Title</title>
    <linkhref="@Url.Content("~/Content/Site.css")"rel="stylesheet"type="text/css"/>
    <scriptsrc="@Url.Content("~/Scripts/jquery-
1.5.1.min.js")"type="text/javascript"></script>
    <scriptsrc="@Url.Content("~/Scripts/modernizr-
1.7.min.js")"type="text/javascript"></script>
</head>
<body>
    <divclass="page">
        <header>
            <divid="title">
                 <h1>MVC Movie App</h1>
            </div>
<divid="logindisplay">
                 @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                 <ulid="menu">
                     <li>@Html.ActionLink("Home", "Index", "Home")</li>
                     <li>@Html.ActionLink("About", "About", "Home")</li>
                 </ul>
            </nav>
        </header>
        <sectionid="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>
Now, let's change the title of the Index page (view).

Open MvcMovieViewsHelloWorldIndex.cshtml. There are two places to make a change: first, the text that
appears in the title of the browser, and then in the secondary header (the <h2> element). You'll make
them slightly different so you can see which bit of code changes which part of the app.
@{
     ViewBag.Title = "Movie List";
}

<h2>My Movie List</h2>

<p>Hello from our View Template!</p>
To indicate the HTML title to display, the code above sets a Title property of the ViewBag object (which
is in theIndex.cshtml view template). If you look back at the source code of the layout template, you’ll
notice that the template uses this value in the <title> element as part of the <head> section of the
HTML. Using this approach, you can easily pass other parameters between your view template and your
layout file.
Run the application and browse to http://localhost:xx/HelloWorld. Notice that the browser title, the
primary heading, and the secondary headings have changed. (If you don't see changes in the browser,
you might be viewing cached content. Press Ctrl+F5 in your browser to force the response from the server
to be loaded.)
Also notice how the content in the Index.cshtml view template was merged with the _Layout.cshtml view
template and a single HTML response was sent to the browser. Layout templates make it really easy to
make changes that apply across all of the pages in your application.
Our little bit of "data" (in this case the "Hello from our View Template!" message) is hard-coded, though.
The MVC application has a "V" (view) and you've got a "C" (controller), but no "M" (model) yet. Shortly,
we'll walk through how create a database and retrieve model data from it.


Passing Data from the Controller to the View
Before we go to a database and talk about models, though, let's first talk about passing information from
the controller to a view. Controller classes are invoked in response to an incoming URL request. A
controller class is where you write the code that handles the incoming parameters, retrieves data from a
database, and ultimately decides what type of response to send back to the browser. View templates can
then be used from a controller to generate and format an HTML response to the browser.

Controllers are responsible for providing whatever data or objects are required in order for a view
template to render a response to the browser. A view template should never perform business logic or
interact with a database directly. Instead, it should work only with the data that's provided to it by the
controller. Maintaining this "separation of concerns" helps keep your code clean and more maintainable.

Currently, the Welcome action method in the HelloWorldController class takes a name and
a numTimes parameter and then outputs the values directly to the browser. Rather than have the
controller render this response as a string, let’s change the controller to use a view template instead. The
view template will generate a dynamic response, which means that you need to pass appropriate bits of
data from the controller to the view in order to generate the response. You can do this by having the
controller put the dynamic data that the view template needs in a ViewBag object that the view template
can then access.
Return to the HelloWorldController.cs file and change the Welcome method to add
a Message and NumTimes value to the ViewBag object. ViewBag is a dynamic object, which means you
can put whatever you want in to it; the ViewBagobject has no defined properties until you put something
inside it. The complete HelloWorldController.cs file looks like this:
usingSystem.Web;
usingSystem.Web.Mvc;

namespaceMvcMovie.Controllers
{
    publicclassHelloWorldController:Controller
    {
        publicActionResultIndex()
        {
            returnView();
        }

         publicActionResultWelcome(string name,intnumTimes=1)
         {
             ViewBag.Message="Hello "+ name;
             ViewBag.NumTimes=numTimes;

              returnView();
         }
    }
}
Now the ViewBag object contains data that will be passed to the view automatically.
Next, you need a Welcome view template! In the Debug menu, select Build MvcMovie to make sure the
project is compiled.
Then right-click inside the Welcome method and click Add View. Here's what the Add View dialog box
looks like:
Click Add, and then add the following code under the <h2> element in the new Welcome.cshtml file. You'll
create a loop that says "Hello" as many times as the user says it should. The complete Welcome.cshtml file
is shown below.
@{
     ViewBag.Title = "Welcome";
}

<h2>Welcome</h2>

<ul>
   @for (int i=0; i <ViewBag.NumTimes; i++) {
      <li>@ViewBag.Message</li>
   }
</ul>
Run the application and browse to the following URL:
http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4
Now data is taken from the URL and passed to the controller automatically. The controller packages the
data into aViewBag object and passes that object to the view. The view then displays the data as HTML to
the user.




Well, that was a kind of an "M" for model, but not the database kind. Let's take what we've learned and
create a database of movies.

More Related Content

What's hot

LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 
IE8 Dev Overview_pp2003
IE8 Dev Overview_pp2003IE8 Dev Overview_pp2003
IE8 Dev Overview_pp2003Wes Yanaga
 
Create rest webservice for oracle public api using java class via jdeveloper
Create rest webservice for oracle public api using java class via jdeveloperCreate rest webservice for oracle public api using java class via jdeveloper
Create rest webservice for oracle public api using java class via jdevelopershravan kumar chelika
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCBarry Gervin
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JSAkshay Mathur
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014Sarah Hudson
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library 10Clouds
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvcGuo Albert
 
Csphtp1 20
Csphtp1 20Csphtp1 20
Csphtp1 20HUST
 
Part 2 generating a client_from_wsdl
Part 2 generating a client_from_wsdlPart 2 generating a client_from_wsdl
Part 2 generating a client_from_wsdlkrishmdkk
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular UJoonas Lehtinen
 
Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS FrameworkRaveendra R
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinBarry Gervin
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 

What's hot (20)

LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 
IE8 Dev Overview_pp2003
IE8 Dev Overview_pp2003IE8 Dev Overview_pp2003
IE8 Dev Overview_pp2003
 
Create rest webservice for oracle public api using java class via jdeveloper
Create rest webservice for oracle public api using java class via jdeveloperCreate rest webservice for oracle public api using java class via jdeveloper
Create rest webservice for oracle public api using java class via jdeveloper
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014
 
Angular JS
Angular JSAngular JS
Angular JS
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Csphtp1 20
Csphtp1 20Csphtp1 20
Csphtp1 20
 
Part 2 generating a client_from_wsdl
Part 2 generating a client_from_wsdlPart 2 generating a client_from_wsdl
Part 2 generating a client_from_wsdl
 
Training On Angular Js
Training On Angular JsTraining On Angular Js
Training On Angular Js
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
 
Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS Framework
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Angular js
Angular jsAngular js
Angular js
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
JavaScript
JavaScriptJavaScript
JavaScript
 

Similar to Adding a view

Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web MahmoudOHassouna
 
Introduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptxIntroduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptxKunal Kalamkar
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Meteor + Ionic Introduction
Meteor + Ionic IntroductionMeteor + Ionic Introduction
Meteor + Ionic IntroductionLearningTech
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101Rich Helton
 
MongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch TutorialMongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch TutorialMongoDB
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S GuideAlicia Buske
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)IT PROGRAMMING WORLD
 

Similar to Adding a view (20)

ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
Starting with angular js
Starting with angular js Starting with angular js
Starting with angular js
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
Introduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptxIntroduction to Web Technologies PPT.pptx
Introduction to Web Technologies PPT.pptx
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Web technologies part-2
Web technologies part-2Web technologies part-2
Web technologies part-2
 
Meteor + Ionic Introduction
Meteor + Ionic IntroductionMeteor + Ionic Introduction
Meteor + Ionic Introduction
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
MongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch TutorialMongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch Tutorial
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
 
Mvc summary
Mvc summaryMvc summary
Mvc summary
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
 

More from Nhan Do

Thay đổi bất thường trên da
Thay đổi bất thường trên daThay đổi bất thường trên da
Thay đổi bất thường trên daNhan Do
 
đIều trị bệnh zona thần kinh bằng đông y
đIều trị bệnh zona thần kinh bằng đông yđIều trị bệnh zona thần kinh bằng đông y
đIều trị bệnh zona thần kinh bằng đông yNhan Do
 
Nguy hiểm khi nghiền thuốc thành bột
Nguy hiểm khi nghiền thuốc thành bộtNguy hiểm khi nghiền thuốc thành bột
Nguy hiểm khi nghiền thuốc thành bộtNhan Do
 
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnh
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnhLạc (đậu phộng) là “sát thủ” của 6 loại bệnh
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnhNhan Do
 
đậU nành botox của da
đậU nành   botox của dađậU nành   botox của da
đậU nành botox của daNhan Do
 
Các món ăn khiến bạn xi hoi
Các món ăn khiến bạn xi hoiCác món ăn khiến bạn xi hoi
Các món ăn khiến bạn xi hoiNhan Do
 
ăN để chống... nhăn
ăN để chống... nhănăN để chống... nhăn
ăN để chống... nhănNhan Do
 
9 “thủ phạm” gây mất ngủ
9 “thủ phạm” gây mất ngủ9 “thủ phạm” gây mất ngủ
9 “thủ phạm” gây mất ngủNhan Do
 

More from Nhan Do (8)

Thay đổi bất thường trên da
Thay đổi bất thường trên daThay đổi bất thường trên da
Thay đổi bất thường trên da
 
đIều trị bệnh zona thần kinh bằng đông y
đIều trị bệnh zona thần kinh bằng đông yđIều trị bệnh zona thần kinh bằng đông y
đIều trị bệnh zona thần kinh bằng đông y
 
Nguy hiểm khi nghiền thuốc thành bột
Nguy hiểm khi nghiền thuốc thành bộtNguy hiểm khi nghiền thuốc thành bột
Nguy hiểm khi nghiền thuốc thành bột
 
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnh
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnhLạc (đậu phộng) là “sát thủ” của 6 loại bệnh
Lạc (đậu phộng) là “sát thủ” của 6 loại bệnh
 
đậU nành botox của da
đậU nành   botox của dađậU nành   botox của da
đậU nành botox của da
 
Các món ăn khiến bạn xi hoi
Các món ăn khiến bạn xi hoiCác món ăn khiến bạn xi hoi
Các món ăn khiến bạn xi hoi
 
ăN để chống... nhăn
ăN để chống... nhănăN để chống... nhăn
ăN để chống... nhăn
 
9 “thủ phạm” gây mất ngủ
9 “thủ phạm” gây mất ngủ9 “thủ phạm” gây mất ngủ
9 “thủ phạm” gây mất ngủ
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 

Adding a view

  • 1. Adding a View (C#) Tutorials By Rick Anderson|January 12, 2011 In this section you're going to modify the HelloWorldController class to use view template files to cleanly encapsulate the process of generating HTML responses to a client. You'll create a view template file using the new Razor view engine introduced with ASP.NET MVC 3. Razor- based view templates have a .cshtml file extension, and provide an elegant way to create HTML output using C#. Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Start by using a view template with the Index method in the HelloWorldController class. Currently the Indexmethod returns a string with a message that is hard-coded in the controller class. Change the Index method to return a View object, as shown in the following: publicActionResultIndex() { returnView(); } This code uses a view template to generate an HTML response to the browser. In the project, add a view template that you can use with the Index method. To do this, right-click inside the Index method and click Add View. The Add View dialog box appears. Leave the defaults the way they are and click the Add button:
  • 2. The MvcMovieViewsHelloWorld folder and the MvcMovieViewsHelloWorldIndex.cshtml file are created. You can see them in Solution Explorer:
  • 3. The following shows the Index.cshtml file that was created:
  • 4. Add some HTML under the <h2> tag. The modified MvcMovieViewsHelloWorldIndex.cshtml file is shown below. @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p>Hello from our View Template!</p> Run the application and browse to the HelloWorld controller (http://localhost:xxxx/HelloWorld). The Index method in your controller didn't do much work; it simply ran the statement return View(), which specified that the method should use a view template file to render a response to the browser. Because you didn't explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to
  • 5. using the Index.cshtml view file in the ViewsHelloWorldfolder. The image below shows the string hard- coded in the view. Looks pretty good. However, notice that the browser's title bar says "Index" and the big title on the page says "My MVC Application." Let's change those. Changing Views and Layout Pages First, you want to change the "My MVC Application" title at the top of the page. That text is common to every page. It actually is implemented in only one place in the project, even though it appears on every page in the application. Go to the /Views/Shared folder in Solution Explorer and open the _Layout.cshtml file. This file is called a layout pageand it's the shared "shell" that all other pages use.
  • 6. Layout templates allow you to specify the HTML container layout of your site in one place and then apply it across multiple pages in your site. Note the @RenderBody() line near the bottom of the file. RenderBody is a placeholder where all the view-specific pages you create show up, "wrapped" in the layout page. Change the title heading in the layout template from "My MVC Application" to "MVC Movie App".
  • 7. <divid="title"> <h1>MVC Movie App</h1> </div> Run the application and notice that it now says "MVC Movie App". Click the About link, and you see how that page shows "MVC Movie App", too. We were able to make the change once in the layout template and have all pages on the site reflect the new title. The complete _Layout.cshtml file is shown below: <!DOCTYPE html> <html> <head> <metacharset="utf-8"/> <title>@ViewBag.Title</title> <linkhref="@Url.Content("~/Content/Site.css")"rel="stylesheet"type="text/css"/> <scriptsrc="@Url.Content("~/Scripts/jquery- 1.5.1.min.js")"type="text/javascript"></script> <scriptsrc="@Url.Content("~/Scripts/modernizr- 1.7.min.js")"type="text/javascript"></script> </head> <body> <divclass="page"> <header> <divid="title"> <h1>MVC Movie App</h1> </div>
  • 8. <divid="logindisplay"> @Html.Partial("_LogOnPartial") </div> <nav> <ulid="menu"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> </ul> </nav> </header> <sectionid="main"> @RenderBody() </section> <footer> </footer> </div> </body> </html> Now, let's change the title of the Index page (view). Open MvcMovieViewsHelloWorldIndex.cshtml. There are two places to make a change: first, the text that appears in the title of the browser, and then in the secondary header (the <h2> element). You'll make them slightly different so you can see which bit of code changes which part of the app. @{ ViewBag.Title = "Movie List"; } <h2>My Movie List</h2> <p>Hello from our View Template!</p> To indicate the HTML title to display, the code above sets a Title property of the ViewBag object (which is in theIndex.cshtml view template). If you look back at the source code of the layout template, you’ll notice that the template uses this value in the <title> element as part of the <head> section of the HTML. Using this approach, you can easily pass other parameters between your view template and your layout file. Run the application and browse to http://localhost:xx/HelloWorld. Notice that the browser title, the primary heading, and the secondary headings have changed. (If you don't see changes in the browser, you might be viewing cached content. Press Ctrl+F5 in your browser to force the response from the server to be loaded.) Also notice how the content in the Index.cshtml view template was merged with the _Layout.cshtml view template and a single HTML response was sent to the browser. Layout templates make it really easy to make changes that apply across all of the pages in your application.
  • 9. Our little bit of "data" (in this case the "Hello from our View Template!" message) is hard-coded, though. The MVC application has a "V" (view) and you've got a "C" (controller), but no "M" (model) yet. Shortly, we'll walk through how create a database and retrieve model data from it. Passing Data from the Controller to the View Before we go to a database and talk about models, though, let's first talk about passing information from the controller to a view. Controller classes are invoked in response to an incoming URL request. A controller class is where you write the code that handles the incoming parameters, retrieves data from a database, and ultimately decides what type of response to send back to the browser. View templates can then be used from a controller to generate and format an HTML response to the browser. Controllers are responsible for providing whatever data or objects are required in order for a view template to render a response to the browser. A view template should never perform business logic or interact with a database directly. Instead, it should work only with the data that's provided to it by the controller. Maintaining this "separation of concerns" helps keep your code clean and more maintainable. Currently, the Welcome action method in the HelloWorldController class takes a name and a numTimes parameter and then outputs the values directly to the browser. Rather than have the controller render this response as a string, let’s change the controller to use a view template instead. The view template will generate a dynamic response, which means that you need to pass appropriate bits of data from the controller to the view in order to generate the response. You can do this by having the
  • 10. controller put the dynamic data that the view template needs in a ViewBag object that the view template can then access. Return to the HelloWorldController.cs file and change the Welcome method to add a Message and NumTimes value to the ViewBag object. ViewBag is a dynamic object, which means you can put whatever you want in to it; the ViewBagobject has no defined properties until you put something inside it. The complete HelloWorldController.cs file looks like this: usingSystem.Web; usingSystem.Web.Mvc; namespaceMvcMovie.Controllers { publicclassHelloWorldController:Controller { publicActionResultIndex() { returnView(); } publicActionResultWelcome(string name,intnumTimes=1) { ViewBag.Message="Hello "+ name; ViewBag.NumTimes=numTimes; returnView(); } } } Now the ViewBag object contains data that will be passed to the view automatically. Next, you need a Welcome view template! In the Debug menu, select Build MvcMovie to make sure the project is compiled.
  • 11. Then right-click inside the Welcome method and click Add View. Here's what the Add View dialog box looks like:
  • 12. Click Add, and then add the following code under the <h2> element in the new Welcome.cshtml file. You'll create a loop that says "Hello" as many times as the user says it should. The complete Welcome.cshtml file is shown below. @{ ViewBag.Title = "Welcome"; } <h2>Welcome</h2> <ul> @for (int i=0; i <ViewBag.NumTimes; i++) { <li>@ViewBag.Message</li> } </ul> Run the application and browse to the following URL:
  • 13. http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4 Now data is taken from the URL and passed to the controller automatically. The controller packages the data into aViewBag object and passes that object to the view. The view then displays the data as HTML to the user. Well, that was a kind of an "M" for model, but not the database kind. Let's take what we've learned and create a database of movies.