官术网_书友最值得收藏!

Adding Views

So far, we were returning a simple string from the controller. Although that explains the concept of how the Controller and action methods works, it is not of much practical use.

Let's create a new action method named, Index2:


Go to https://goo.gl/UhaHyz to access the code.
public IActionResult Index2()
{
return View(); // View for this 'Index2' action method
}

Now, we have created the action method that returns a view, but we have still not added the view. By convention, ASP.NET MVC would try to search for our view in the Views\{ControllerName}\{ActionMethod.cshtml} folder. With respect to the preceding example, it will try to search for Views\Home\Index2.cshtml. Please note that the name of the controller folder is Home, not HomeController. The prefix is only needed as per convention. As this folder structure and file are not available, you'll get a 500 Internal Server Error when you try to access this action method through the URL http://localhost:50140/Home/Index2.

So, let us create a folder structure. Right-click on the solution, navigate to Add | New Folder from the context menu, create a folder called Views, and then create a subfolder by the name Home within the Views folder:

Right-click on the Home folder, and navigate to Add | New Item from the context menu. A dialog will appear, as shown in the below screenshot. Give the name of the file as Index2.cshtml, as our action method name is Index2. cshtml is the Razor view engine (this will be discussed in detail in The View Engine and the Razor View Engine section of the next chapter) extension used when you are using C#.

A file by the name Index2.cshtml will be created with the following content when you click on the Add button in the preceding screen:

@* is the comment syntax in the Razor view engine. You can write any C# code within the @{} block.

Let us add a simple HTML block after the generated code:

<html>
<body>
Hello! This is <b>my first View</b>
</body>
</html>

Now, when you run the application, you will get the following output:

The following diagram explains the request flow and how we generate the response through the View:

主站蜘蛛池模板: 新安县| 北京市| 濮阳县| 白水县| 老河口市| 永修县| 孟村| 雷山县| 泉州市| 安达市| 新平| 丰顺县| 盖州市| 清新县| 大丰市| 名山县| 博野县| 南丹县| 休宁县| 江安县| 屯门区| 濮阳市| 祥云县| 呼图壁县| 奉贤区| 汕尾市| 和平县| 马尔康县| 天津市| 淳安县| 汉寿县| 汝州市| 攀枝花市| 岗巴县| 芒康县| 武宁县| 上杭县| 苍南县| 樟树市| 上杭县| 烟台市|