ASP.NET Core MVC Tutorial Part 1

Hello, I have been interested in ASP.NET Core for some time now and have been playing about with MVC including creating routes, controllers etc. So I thought a great way of expanding and retaining my knowledge of MVC would be to write tutorials on this topic.

What is MVC?

We first have to ask ourselves what exactly is MVC? MVC is an architectural pattern i.e. a way a building software which separates the software into 3 main concerns, these being Models, Views & Controllers. One of the main reasons to implement an MVC software project is that it helps achieve a principal called “separation of concerns” which promotes the idea that software should be separated based on the type of functionality it performs i.e. the Model will contain the business logic such as properties like ID, firstName, lastName. The view will be responsible for showing content to the user through a user interface using a view engine such as Razor, in addition, the controller helps to choose which view to show to the user depending on different links clicked as well as work with the model data. The separation of these 3 components helps to ensure that testing is easy to do.

I will be using Rider to create a simple solution in this tutorial where we create a controller that maps to a different route and will show different text on our page, to do this we will need to create a class file that acts as a controller and a .cshtml filethat will contain some html content to show to the user. The file extension is .cshtml because we are using the Razor View Engine.

So I have created my ASP.NET Core MVC project in Rider (you can do the same if you use Visual Studio and I think maybe even Visual Studio Code)

So once this project has generated successfully you will see multiple folders including Models, Views, Controllers. Within the Controller folder there should already be a controller file named “Home”. Within this folder create another class file named “TutorialOneController” you must append the word “Controller” to the file name.

The next thing to do is for the “TutorialOneController” class to inherit from the “Controller” class like below.

public class TutorialOneController:Controller
{


}

This allows us to use methods and properties of the controller class that can perform actions upon HTTP requests that are made to the project.

As you can see already there is an “Index” and “Welcome” method within the class. Every method in the class with a public access modifier can be called as a HTTP endpoint so we could return a “.cshtml” file or “View” if we wished inside the method.

Since we have named the file “TutorialOne” if we were to enter the below as a URL.

https://localhost:5001/TutorialOne

The content that will show on the page will be

This is my default action...

Because we have NOT specified an endpoint within “TutorialOne” so it will run the default method which in this case is the “index” method. The reason for this can be seen if you open the “Startup.cs” file and scroll down to the bottom and you can see a line of code like the below.

pattern: "{controller=Home}/{action=Index}/{id?}");

So when you run the project and do not enter any url segments or parameters then the default controller that will run will be “Home” and the default “action” will be “index” so the “index” public method will be run and that is why the text inside of the “index” method is shown to the user.

However, if we were to enter.

https://localhost:5001/TutorialOne/Welcome

Then the content inside the “Welcome” method will run as we are calling the “Welcome” method within the “TutorialOne” controller.

Furthermore, we don’t want to always return static text to the user we want to showcase a page to the user with dynamic content on it. The way to do this is using a “View” from some sort of View engine such as Razor.

In your Views folder create another folder inside of it called “TutorialOne” and inside of the “TutorialOne” folder create a .cshtml file named “Welcome”. For the moment it doesn’t matter if you choose a pre-filled view file or not we will only be entering minimal content into it.

Once you have done this enter the below code into the view file.

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

<h2>My Welcome page!</h2>

<p>Hello from my welcome page, my favourite page...</p>

The “@” symbol is used to signify server side C# code within a .cshtml file. An example of this is below.

<h2>@DateTime.Now</h2>

Which uses the C# DateTime struct to showcase the current time to the user.

Now since we have created the file we want to somehow show the content to the user, to do this we will need to navigate back to our “TutorialOneController” Controller file and inside the “Welcome” method change the return type to “ActionResult” and inside the method return a “View” and not a string like the below.

public ActionResult Welcome()
{
return View();
}

ActionResult

Methods within Controllers are referred to as action methods as they perform an action such as returning a View to return an HTML response, however, action methods must be public, cannot be overloaded or be a static method.

In addition, MVC has a plethora of Result classes which represent different types of responses such as a string, JavaScript, HTML or a file. Below are a few.

ViewResult — HTML markup

JavaScriptResult — JavaScript Script

HttpUnauthorizedResult — Returns a HTTP 403 forbidden status

ActionResult is a “base class” for those Result classes mentioned above so it is able to be a return type of an action method which returns any of the result classes above.

ViewData

ViewData is a dictionary type so you can set a key name of whatever you like as long as it is a string to equal a value and is used to transfer data from a controller to a view, however, the data cannot be transferred the other way around from view to controller. So you could assign a ViewData key equal to data that is returned from a database or a json response and then in the .cshtml file loop over this data to display to the user.

So in our first example of ViewData we are setting it in the .cshtml file, however, now we will create one in our Controller.

So navigate to TutorialOneController and inside of the “Welcome” method enter the below above the “return” statement.

public ActionResult Welcome()
{
ViewData["MyFirstWelcome"] = "My first Controller View Data";
return View();
}

So now we can access the “MyFirstWelcome” inside of the “Welcome” file like the below.

<p>@ViewData["MyFirstWelcome"]</p>

So our “Welcome” cshtml file will now look like this.

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

<h2>My Welcome page!</h2>

<p>Hello from my welcome page, my favourite page...</p>
<p>@ViewData["MyFirstWelcome"]</p>

Run the project and navigate to the Welcome page and you should see the below.

As you can see the text from the “ViewData[“MyFirstWelcome”]” is on the page.

We can also add to ViewData by using a list function “Add” and specify a key value pair where the key is a string and the value is an object.

ViewData.Add("MyID",1);
ViewData.Add(new KeyValuePair<string, object>("Greeting","Hi there top of the morning to ya!"));

So we can access “MyID” and “Greeting” the same way as before.

<h3>@ViewData["MyID"]</h3>
<h2>@ViewData["Greeting"]</h2>

This is just a very brief and basic introduction into the world of ASP.NET Core MVC which has a plethora to offer to every software developer. It has been a bit of a struggle sometimes getting to grips to how some of the code is laid out with how to communicate controllers and views etc but although it is difficult it is also incredibly intriguing and more rewarding when I do begin to finally understand the process of this software architecture pattern!

I hope you have learnt something from this tutorial as I have had a lot of fun getting to grips with MVC recently and if you see anything in my article that could be changed/improved feel free to respond to the article and I will see what I can do.

Thanks again for reading, here is my blog too (it is still in progress as I’m struggling to find time for it) — https://cowboycode.co.uk/

Software Developer in the UK. With a keen passion for React Native & C#. Blog — https://cowboycode.co.uk/