matomo

Getting to know the Controller
Skip to main content

Development blog

This blog contains posts mostly regarding development in asp.net core. System Engineering and DevOps topics are also covered in this blog.
Most of the content published on this homepage is a practical approach to official documentations like docs.microsoft.com. I try to link the related parts of said documentations in every post.

If you feel that you are able to improve this blog by providing any kind of update or feedback, please do so via the comments section or the contact form.

Enjoy reading!

Getting to know the Controller

In the last article, I made an overview of the project, this time I will set focus on the controller.

The initial code looks like this

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using TestProject.Models;
namespace TestProject.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

The class HomeController has three Methods. Each is a Site that can be rendered.

public IActionResult Index()

and

public IActionResult Privacy()

are the two Sites we normally would visit and

public IActionResult Error()

will be rendered as soon as some server errors appear.

Inside each Method, the View() function is returned. This will find the associated .cshtml file which is beneath the Views folder. Also, the respective controller's name is taken into account. The Index() method will render /Views/Home/Index.cshtml and the Privacy() method /Views/Home/Privacy.cshtml. If there is no Error.cshtml in /Views/Home/, the app will next check the /Views/Shared/ folder.


Categories: Default, asp.net core

DevOps Engineer at TIMEWARP IT Consulting GmbH

Read more posts by Marius Steinbach