using Microsoft.AspNetCore.Mvc;
namespace Project.Controllers
{
public class MyFirstController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
}
}
Now we will add a View in your application from controller first we need to right click on controller Action and click on "Add View" option. A window will open. In this window we need to select the option Razor View and click on Add button. Here a new window will open in this window we need to provide the view name if it is not available.
Here we will get option to select the Layout. Don't select the Layout file, this applies the default Layout file to the newly created view.
Now in your view add some basic code to display a form.
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @Id = "formdata", @enctype = "multipart/form-data" }))
{
<div class="text-center">
<b>Name:</b>
@Html.TextBox("Name", "", new { @class = "form-control" })
<br />
<input type="submit" value="Submit" />
</div>
}
Now we will check the shared folder for layout file. Here we will have a default Layout file named as _Layout.
Now let's open the layout file and add some text to validate the assigned layout file. In layout file just above the @RenderBody() method i have added the text with H1 tag. Please check the below code.
<div class="container">
<main role="main" class="pb-3">
<h1>Default Layout</h1>
@RenderBody()
</main>
</div>
In above please check highlighted code. This will help us to identify the default and custom layout. Now run the application to check the output.Now we will make some modification in our custom layout page. I have added an H1 tag as identifier. Please check the below code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/Project.styles.css" asp-append-version="true" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
<h1>Custom Layout</h1>
@RenderBody()
</div>
</body>
</html>
Now we will assign the custom Layout page to view. For this we will open the View and add a Layout property with wit the path of the custom layout file which is is shared folder.@{
ViewData["Title"] = "Home Page";
Layout = "~/Views/Shared/_CustomLayout.cshtml";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @Id = "formdata", @enctype = "multipart/form-data" }))
{
<div class="text-center">
<b>Name:</b>
@Html.TextBox("Name", "", new { @class = "form-control" })
<br />
<input type="submit" value="Submit" />
</div>
}
Please check the highlighted part of the above code. This code will help us to make the custom layout available for view. Now Run the application to check the output.