In this section, you need to modify the Helloworldcontroller class to use the view template file, which generates a clean and elegant wrapper to return the HTML to the client browser.
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 extension and provides an elegant way to create the HTML that 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 and smooth coding workflow is achieved.
The index method currently in the Controller class returns a hard-coded string. Changing the index method returns a View object, such as the following sample 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 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 file that has been created in Solution Explorer :
The index.cshtml file that has been created is displayed:
Add the following HTML after the
<p>hello from our View template!</p>
The complete mvcmovie\helloworld\index.cshtml file is shown below.
@{
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> highlighted in yellow above, and click the "Compatibility View" button in IE browser, The icon changes from the icon to a solid color. 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 .
Views are the way data is presented, and this knowledge can be better used for MVC development. At the same time, some development tools are also available to help with the development process. ComponentOne Studio ASP. This lightweight control integrates seamlessly with visual Studio and is fully compatible with MVC6 and ASP. NET 5.0, which greatly increases development efficiency.
"Translation Reprint" "Official Tutorial" ASP. NET MVC4 Getting Started Guide (3): Adding a View