First ASP.NET Core 5.0 MVC Application

First ASP.NET Core 5.0 MVC Application

In this ASP.NET Core Tutorial you will create your first application in Visual Studio 2019.

ASP.NET Core Application in MVC Template

Open Visual Studio, then select Create a new poject from the file menu. This will open the New Project dialog.

You will see ASP.NET Core Web Application option, so select it.

asp.net core web application mvc template

Next you will Configure your new project. So add the name of the project as FirstApp and select the location on your drive where you want this application to be created.

configure project

Click the Create button to continue. You will reach a new page which says – Create a new ASP.NET Core web application. Here you have to select the framework, template and authentication.

asp.net core web application (MVC template)

Ensure that .NET Core and ASP.NET Core 5.0 are selected from the drop-down menus, select Web Application (Model-View-Controller) template.

Click the Change Authentication button and select Authentication as No Authentication. Option of Enable Docker Support should be un-checked.

Finally click the Create button to create your application.

You are ready to run your application. Select Start Debugging from the Debug menu (if it prompts you to enable debugging, just click the OK button). You can also start debugging by using a shortcut which is F5 key.

Visual Studio will build your application and open it on your default browser. It will look something like as shown on the below image.

first application in asp.net core mvc
Here you have chosen the MVC Template so the necessary MVC folders and files are automatically created by Visual Studio. You can open the ‘Solution Explorer’ which is given on the right corner of Visual Studio and see all these files. Had you chosen the other option, which is the ‘Empty’ template one, then you have to create these MVC files and folders one-by-one from the file menu.
mvc files in solution explorer

MVC files and folders

Let us understand about these files and folders in your application.

  • wwwroot – contains the static files like images, scripts, external frameworks and libraries like Bootstrap, jQuery.
  • Controllers – This folder contains the controller files.
  • Models – This folder contains the model files.
  • Views – This folder contains the view files.
  • appsettings.json – This file contains configuration settings of the application. You can use it to store database connection string, application variable values and other informations.
  • program.cs – It is your application’s entry point which starts when you run your application. Here you create your application host, chose the web server and call the startup.cs file.
  • startup.cs – This file is called from the program.cs file. Here you add services and configure the HTTP pipeline. You also write URL Routes in this file.

The above are just a brief description of these MVC files an folder. You will get complete understanding on these files as you carry on with these tutorials.

There are lots of configurations in ASP.NET Core which I have covered in the tutorial called Configuring Application in ASP.NET Core. Make sure to read it after you complete this tutorial.

Adding a Controller

As explained earlier a ASP.NET Core Controller is a C# class which handles all incoming HTTP requests. A Controller can have one or more action methods. Each action methods can be invoked from the web by some URL’s. For example: If a controller named ‘Home’ has an action method named ‘Calculate’ then this action method can be invoked by opening URL – /Home/Calculate on the browser.

By default, the Visual Studio adds the ‘Home’ controller. Now you will add a new controller, so right click the Controllers folder on the Solutions Explorer. Then select Add ➤ Controller on the menu.

You will get a new dialog box, here select the first option saying – MVC Controller – Empty and click ‘Add’ button.

add new controller

Next another dialog box opens where you can give the name to the controller. Name this controller – FirstController, and click the ‘Add’ button.

set controller name

The new controller gets added to your Application and VS opens it up for editing. By default it will have the following code given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
 
namespace FirstApp.Controllers
{
    public class FirstController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Action method returning String

The Controller has one action method which is named Index. I am going to change this method so that it returns a string.

Controllers and Action methods are fundamental parts of ASP.NET Core. Go through the article called Action methods in ASP.NET Core to understand how each of them works and how you can extract their full power.

So, change this action method to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
 
namespace FirstApp.Controllers
{
    public class FirstController : Controller
    {
        public string Index()
        {
            return "Hello World";
        }
    }
}

Now the action method returns a string – ‘Hello World’.

Let us invoke this action on the browser. Run the application by clicking Debug ➤ Start Debugging or press the F5 key. Visual Studio will open the browser showing the Home page.

Change the URL on the browser to – http://localhost:59009/First/Index and press enter. You will see – ‘Hello World’ on the browser as shown below.

invoking action browserHere 59009 is the port of my application, in your case it will be different. So make sure you keep your application port in the browser url.
The ‘Index’ action method is the default action method as set on the ‘startup.cs’ file, so you don’t have to explicitly specify it on the browser URL. The above action can simply be invoked by http://localhost:59009/First.

The action method which I just made returns a string therefore there is no need to create a view. In general, most of the time you will need actions that returns a ‘View’. So for these actions the return type should be IActionResult

Action method returning View

Add a new action method to the controller and name it ‘Hello’. It means it should have the return type of IActionResult as it is returning a View.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
 
namespace FirstApp.Controllers
{
    public class FirstController : Controller
    {
        public string Index()
        {
            return "Hello World";
        }
 
        public IActionResult Hello()
        {
            return View();
        }
    }
}

Run your application (shortcut F5 key) and then go to the action method’s URL – http://localhost:59009/First/Hello.

You will see that the application is trying to find the view, as shown in the error message displayed below.

asp.net core mvc search location of the view

The error states:

InvalidOperationException: The view 'Hello' was not found. The following locations were searched:
/Views/First/Hello.cshtml
/Views/Shared/Hello.cshtml

This is a helpful message explaining the error occurred due to absence of View file in the application. ASP.NET Core MVC Views are stored in the Views folder and organized into subfolders.

Views associated with the ‘First’ Controller are stored in ‘Views/First’ folder. Views, not specific to a single controller, are stored in a folder called ‘Views/Shared’. So you create get rid of this error by creating ‘Hello’ View in either ‘Views/First’ or ‘Views/Shared’.

But there is a catch, if you put ‘Hello’ View inside the ‘Views/Shared’ folder, and another Controller, suppose ‘Another’, which also has an action method by the same name – ‘Hello’, and it too does not has its specific view, then whenever the ‘Hello’ action of any controller (‘First’ or ‘Another’) is invoked then Views ➤ Shared ➤ Hello will be called.

In short both the below URL will invoke the View – Views/Shared/Hello, provided there aren’t have specific views:

  • /First/Hello
  • /Another/Hello
MVC framework searches a View of an action method, first in its specific folder, if it does not finds the view, then it searches it in the ‘Shared’ folder. Views have .cshtml file extension.

I will here create specific view for the ‘Hello’ controller.

Right click the Views folder and select Add ➤ New Folder. Name this new folder First.

Next, right click on this ‘First’ folder and select Add ➤ New Item. Then on the dialog box Razor View – Empty. Name your view as ‘Hello’ and finally click the ‘Add’ button to create this view.

creating hello view

VS will create it and opens it for editing. It’s code looks like as shown below:

@{
    ViewData["Title"] = "Hello";
}
 
<h2>Hello</h2>

Just do a small change, change the ‘h2’ tag content to ‘Hello World’ and save the View.

@{
    ViewData["Title"] = "Hello";
}
 
<h2>Hello World</h2>

Now run your application and go the URL – http://localhost:59009/First/Hello.

You will see the view rendered on the browser as shown below:

hello view

You successfully created your first view and invoked it from the browser. Next you will see how to add dynamic data to the View.

For complete understanding of views you have to read Working with ASP.NET Core Views

Adding Dynamic Data to the View

Passing data from Controllers to Views are done in a number of ways. I will explain all these ways to you later on. For here, I will make use of ViewBag which is a dynamic object to assign any type of value.

Just change ‘Hello’ action method to include ‘ViewBag’ code that assigns a variable to a string “Hello World”. I have named the variable as ‘Message’ (it can be any name for the variable).

public IActionResult Hello()
{
    ViewBag.Message = "Hello World";
    return View();
}

The action stores the string on the ‘ViewBag’ variable called Message. Now you have to display this stored string on the View. So change the Hello.cshtml code to this:

@{
    ViewData["Title"] = "Hello";
}
 
<h2>@ViewBag.Message</h2>

The change is just a code inside the h2 tag to @ViewBag.Message. It simply displays the value of the ‘ViewBag’s Message’ variable on the view.

Re-run the application and go to the /First/Hello on the browser. You will get the same result like before but here you have made it dynamic.

You can assign any value to a ViewBag variable like string, int, class object,xml, json, etc. The ViewBag variable is automatically destroyed by MVC once the View is rendered.

Adding Model and transferring its data to View

In this section I will add a Model to the application. I will fill this Model from the Controller and then pass it to the View where it will be displayed. Models are nothing but C# classes.

Their is a video tutorial which you will find helpful – Create Your First Application with ASP.NET Core 5.0

I will add a simple class to the Models folder. So right click the Models folder and select Add ➤ Class. Name the class as ‘Person.cs’. Add the below properties to it:

using System;
 
namespace FirstApp.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Location { get; set; }
    }
}

It is a simple class that contains 3 properties – Nam, Age and Location. Now I will fill these 3 properties with values in the Controller.

Lean how to do database programming with ADO.NET. Check this tutorial for it – Working with ADO.NET in ASP.NET Core

Go to the ‘First’ Controller and add a new action method by the name ‘Info’. The code of the Controller looks like this:

using FirstApp.Models;
using Microsoft.AspNetCore.Mvc;
 
namespace FirstApp.Controllers
{
    public class FirstController : Controller
    {
        // Index Action
 
        // Hello Action
 
        public IActionResult Info()
        {
            Person person = new Person();
            person.Name = "John";
            person.Age = 18;
            person.Location = "United States";
            return View(person);
        }
    }
}

In the Info Action Method I have created a new object (‘person’, note small ‘p’) for the Model class ‘Person’. Then assigned the Name property as ‘John’, Age property as 18 and Location property as ‘United States’. Finally at the end the ‘person’ object is returned to the View (from code View(person).

To use the ‘Person’ class in the ‘First’ controller you have to import the Models namespace on the Controller at the top- using FirstApp.Models

Now Model is filled in the Controller and we have to show it’s data on the View. So create ‘Info’ view inside the Views ➤ First.

The Info view initially will have the following code:

@{
    ViewData["Title"] = "Info";
}
 
<h2>Info</h2>

Update it by defining the Model type (the class type in general) which it will get from the Controller, on the top like this:

@model Person

Note: It will receive the Model of type ‘Person’ so I have added ‘Person’ there.

Finally, to show the Model data, add the below code to the View:

<p>Name: @Model.Name</p>
<p>Name: @Model.Age</p>
<p>Name: @Model.Location</p>

The View will now look:

@model Person
@{
    ViewData["Title"] = "Info";
}
 
<h2>Info</h2>
<p>Name: @Model.Name</p>
<p>Name: @Model.Age</p>
<p>Name: @Model.Location</p>

Run the application and navigate to /First/Info on the browser. Your Model data will be display like shown on the image below.

view showing model data

You should note that when you define the model type on the view, you use small ‘m’ like @model Person. When you have to show Model properties value then use capital ‘M’ like @Model.Name.

In the next section I will create a basic form where information can be ‘Added’, ‘Updated’, ‘Read’ and ‘Deleted’.

You can download the full codes of this tutorial from the below link:

Download

Conclusion

Congratulations, you just created your first application in ASP.NET Core MVC. You have now understood the basic working of ASP.NET Core and can go on learning other areas of this framework.

In the next tutorial I am making a CRUD based application in ASP.NET Core, make sure to read it at First CRUD application in ASP.NET Core

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate