In this article we will learn How to Customize view in ASP.NET Core MVC ?
Customize view in ASP.NET Core MVC
In ASP.NET Core MVC different types of overloaded version available.
1. View() : Creates a Viewresult object that renders a view to the response.
2. View(object model) : Creates a Viewresult object by specifying a model to be rendered by the view.
3. View(string ViewName) : Creates a Viewresult object by specifying a View Name
4. View(string ViewName, object model) : Creates a Viewresult object by specifying a View Name and the model to be rendered by the view.
Step by step we will see Customize view in ASP.NET Core MVC.
View(string ViewName)
If you don’t want to like this default convention, you can use this overloaded version of the View(string viewName) method, that pass viewName as a parameter, to look for a view file with your own custom name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Demo.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
//You can see pass ViewName as a parameter, to look for a view file with your own custom name.
return View("Index1");
}
}
}
Output
Specifying view file path
Using this overloaded version, we can also specify a view name or a view file path. In the following example, we specified the absolute view file path. So in this case, MVC looks for a view file with name “Demo.cshtml” in “Demo” folder. Hare we not specified the path to the view file, by default, MVC would look for “Index.cshtml” file in “Views/Home” folder.
Key Point
With the absolute path, the .cshtml extension must be specified.
public class HomeController : Controller
{
public ViewResult Index()
{
return View("Demo/Demo.cshtml");
}
}
Output
Key Point
We can use / or ~/. So the following lines of code work the same thing
return View("/Demo/Demo.cshtml");
return View("~/Demo/Demo.cshtml");
Relative View File Path
When we want to specifying a view file path, we can also use a relative path. With relative path we do not specify the file extension .cshtml. In the following example, MVC search for Demo2.cshtml file in “Views/Demo” folder.
public class HomeController : Controller
{
public ViewResult Index()
{
return View("../Demo2/Demo2");
}
}
Output
If you want to achieve Demo.cshtml View from Demo folder. Please Go back up 2 levels in the folder hierarchy, use ../ twice as shown below. In the following example.
public class HomeController : Controller
{
public ViewResult Index()
{
return View("../../Demo/Demo");
}
}
Output