In this section, you need to modify the Helloworldcontroller class to use the view template file, a clean and elegant encapsulation to generate the process of returning to the client browser HTML.
You will create a view template file that uses the Razor view engine introduced by ASP.net MVC 3. The Razor view template file uses the. cshtml file name extension and provides an elegant way to create the HTML you want to output using the C # language. When writing a view template file with razor, the required number of characters and keystrokes is minimized, and a fast, smooth coding workflow is achieved.
The index method currently in the Controller class returns a hard-coded string. Change the index method to return a view object, such as the following example code:
Public ActionResult Index () {return View ();}
The index method above uses a view template to generate an HTML return to the browser. The controller's method (also known as action method), such as the index method above, typically returns a ActionResult (or a type inherited from ActionResult) rather than the original type, such as a string.
In this project, you can use the index method to add a view template. to do this, right-click in the index method, and then click Add View.
The Add View dialog box appears. Leave the default values and click the Add button:
You can see the Mvcmovie\helloworld folder and the mvcmovie\view\helloworld\index.cshtml files that have been created in Solution Explorer:
The following illustration shows the index.cshtml file that has been created:
Add the following HTML after the
Copy Code code as follows:
<p>hello from our View template!</p>
The complete mvcmovie\helloworld\index.cshtml file is shown below.
Copy Code code as follows:
@{
Viewbag.title = "Index";
}
<p>hello from our View template!</p>
Note: If you are using Internet Explorer 9, you will not see the <p>hello from our view template!</p> above with yellow highlighting, click the Compatibility View button, and in IE browser, The icon will change from a solid color icon. Alternatively, you can view this tutorial in Firefox or Chrome.
If you are using Visual Studio 2012, in Solution Explorer, right-click the index.cshtml file and select View in Page Inspector.