First ASP.NET Core MVC Application

First ASP.NET Core MVC Application

In this tutorial you will create your first ASP.NET Core MVC application in Visual Studio 2017.

Creating an Application using MVC Template

Open VS 2017, then select New ➤ Project from the file menu. This will open the New Project dialog.

Navigate to Installed ➤ Visual C# ➤ Web section on the left side of the dialog.

You will see ASP.NET Core Web Application on the middle side of the dialog, select it. Add the name of the project as ‘FirstApp’ and select the location on your drive where you want this application to be created.

asp.net core web application template in visual studio 2017

Click the ‘OK’ button to continue and you will see another dialog box as shown on the image below. This dialog box will ask you to select the framework, template and authentication.

selecting dot net core framework

Ensure that .NET Core and ASP.NET Core 2.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 ‘OK’ 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).

Note – 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

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’, given on the right side of VS, and see all these files. If, on the second dialog box, you choose the ‘Empty’ template 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.
  • bundleconfig.json – Create bundles and minifications of CSS files and scripts. This helps in reducing the file size of these CSS files and scripts, thus making your application lightweight.
  • 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.

Adding a Controller

As explained earlier a 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.

The code of this Controller (FirstController) is 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.

So change the action method like what 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 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 browser

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. Therefore the above action can simply be invoked by – http://localhost:59009/First. Also notice that Visual Studio has directed the browser to port 59009 for me. You will obviously see a different port on your computer.

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, name it ‘Hello’, that has return type of IActionResult and returns 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 you can see MVC trying to find the view, as shown in the error message displayed below.

search location of 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 method explaining the error occurred due to absence of View file in the application. 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 a Controller, first in its specific folder, if it does not find 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 ➤ View, to open ‘Add MVC View’ dialog box. Name your view as ‘Hello’ and finally click the ‘Add’ button to create this view.

creating hello view

VS will create it and open 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.

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, here ‘Message’ (can be any name for the variable), to a string “Hello World”.

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

The action stores the string on the ‘ViewBag’ variable. 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 – @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.

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.

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 had the Models namespace on the Controller – using FirstApp.Models;

Now Model is filled in the Controller. Now I have to show its 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 ares of this framework.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.