Add a view

Add a view to an ASP.NET Core MVC app

Modify the controller method

In this section, you modify the HelloWorldController class to use Razor view files. This cleanly encapsulates the process of generating HTML responses to a client.

View templates are created using Razor, which:

  • Have a .cshtml file extension.

  • Provide an elegant way to create HTML output with C#.

Currently the Index method returns a string with a message in the controller class. In the HelloWorldController class, replace the Index method with the following code:

public IActionResult Index()
{
    return View();
}

The preceding code:

  • Calls the controller's View method.

  • Uses a view template to generate an HTML response.

Controller methods:

  • Are referred to as action methods. For example, the Index action method in the preceding code.

  • Generally, return an IActionResult or a class derived from ActionResult, not a type like string.

Add a view

Right-click on the Views folder, and then Add > New Folder and name the folder HelloWorld.

Right-click on the Views/HelloWorld folder, and then Add > New Item.

In the Add New Item - MvcMovie dialog:

  • In the search box in the upper-right, enter view

  • Select Razor View - Empty

  • Keep the Name box value, Index.cshtml.

  • Select Add

Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

Run the updated code

Navigate to https://localhost:{PORT}/HelloWorld:

  • The Index method in the HelloWorldController ran the statement return View();, which specified that the method should use a view template file to render a response to the browser.

  • A view template file name wasn't specified, so MVC defaulted to using the default view file. When the view file name isn't specified, the default view is returned. The default view has the same name as the action method, Index in this example. The view template /Views/HelloWorld/Index.cshtml is used.

  • The following image shows the string "Hello from our View Template!" hard coded in the view:

When the view file name isn't specified, the default view is returned - The default view has the same name as the action method!

Last updated