AspNetMVC Core1
AspNetMVC Core1
Till now, we have discussed everything using the ASP.NET Core Empty Project
Template and understand the different components of an ASP.NET Core
Application. We also discussed Setting up the MVC Request pipeline in the
ASP.NET Core Web Application.
To create an ASP.NET Core Web Application with the MVC Project template. First,
open Visual Studio 2022 and click the Create a new project tab, as shown in the
image below.
Once you click on the Create a new Project tab, the following Create a new
Project window will open. From this window, select C#, All Platforms, and Web
from the respective dropdowns, as highlighted below. Select the ASP.NET Core
Web App (Model-View-Controller) as the project template, and click
the Next button, as shown in the image below.
1
Once you click on the Next button, it will open the Configure Your New
Project window. Here, you need to provide the necessary information to create a
new ASP.NET Core project. First, give an appropriate name for your project
(SampleMVCWeb), set the location where you want to create this project, and
the solution name for the ASP.NET Core Web application. And finally, click on
the Create button, as shown in the image below.
Once you click the Create button, the following Additional Information window
will open. Please select Framework .NET 8.0 (Long-term support) and
Authentication type None. You must also check the Configure for
HTTPS and do not use top-level statements check boxes. Finally, click the
Create button, as shown in the image below.
2
Once you click the Create Button, the project will be created with the Web
Application (Model-View-Controller) template, i.e., the MVC template, with the
following folder and file structure.
Understanding the ASP.NET Core MVC Project File and Folder Structure:
Connected Services
This section within the Solution Explorer in Visual Studio allows us to easily
connect to external services such as Azure, Office 365, REST APIs, or third-party
services. It helps integrate and configure APIs, SDKs, or services that your
application depends on. It simplifies consuming external services by managing
the necessary configurations and client code generation.
Dependencies Folder
The Dependencies folder contains the NuGet packages and other dependencies
your project relies on. It includes:
Properties Folder
This folder contains the launchSettings.json file, which is used to configure how
the application is launched, including profiles for IIS Express and other
environments. It includes settings for environment variables, application URL, and
other settings related to how the application is run during development. You can
specify different settings for different environments (like Development, Staging,
and Production) in this file.
3
wwwroot Folder
The wwwroot folder is the root folder for all static content your application uses,
such as CSS, JavaScript, and image files. Files in this folder are accessible via a
URL without additional configuration, making it ideal for storing assets directly
needed in client-side interactions.
Controllers Folder
The Controllers folder contains the controller classes. Controllers handle incoming
HTTP requests, process them (often using services and models), and return the
appropriate responses (usually views or JSON data) to the client. The methods
inside controller classes are called actions and mapped to different routes defined
in the application.
Models Folder
The Models folder contains classes that represent the data of the application and
logic to manage the data, i.e., how the data is going to be handled. Models
represent the shape of the data and its business logic. This includes validation
rules, business logic, and data-access logic. These classes are also used to pass
data between the controllers and views. They often correspond to database tables
in applications that use Entity Framework Core. For example, a Product model
might represent a Product table in a database.
Views Folder
The Views folder contains files to generate the HTML content returned to the
client. It typically includes subfolders for each controller, containing the views
associated with each action. These files are typically Razor view files (.cshtml),
which mix HTML markup with C# code for dynamic content generation.
Shared Folder
The Shared folder contains views and partial views that are shared across multiple
other views, such as layout templates (e.g., _Layout.cshtml), error pages, or
partial views used across various pages of the application. The Shared folder is
typically located under the Views directory.
_ViewStart.cshtml File
The _ViewStart.cshtml file is a special file in the Views folder that runs before
every view in the application is executed. It is used to define common settings for
all views, like specifying a common layout file (_Layout.cshtml) for the views. This
makes it ideal for setting layout pages and other common settings.
_ViewImports.cshtml File
4
declarations for namespaces, @inject for dependency injection, and @model
declarations, to be available to all views without having to add them in each view
individually. It helps to avoid repeating the same imports across multiple views.
appsettings.json File
Program.cs File
The Program.cs file is the application’s entry point. It sets up the web host that
will host the app, configures services, logging, configuration sources, and the
HTTP server, and configures the ASP.NET Core application pipeline and services.
The ASP.NET Core Web APP (Model-View-Controller) Project template includes the
required MVC setup by default. To confirm this, open the Program.cs class file
and the framework has added the required MVC Services and MVC Request
processing pipeline, as shown in the image below.
namespace SampleMVCWeb
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add MVC Services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production
scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//MVC Request Processing Pipeline
5
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
}
}
Running the MVC Application:
The ASP.NET Core Web APP (Model-View-Controller) Project template creates the
Home Controller with some views. Let’s run the application and see the output, as
shown below.
In ASP.NET Core MVC Applications, we can pass the data from a controller action
method to a view in many different ways, such as by
using ViewBag, ViewData, TempData, and a Strongly Typed Model. Here, I
will show you how to use ViewData to pass the data from the controller action
method to a view. The other three techniques, i.e., ViewBag, Tempdata, and
Strongly Typed View Model in a another class.
ViewData is a dictionary object in ASP.NET Core MVC that allows us to pass data
from a controller action method to a view. It provides a flexible way to pass data,
allowing us to use key-value pairs. ViewData is useful when we need to pass
dynamic data or data that doesn’t fit well into a strongly typed model. If you go to
the definition of ViewData, you will see that It is a property in the Controller
abstract class, and its type is ViewDataDictionary. This property is also
decorated with the ViewDataDictionary attribute, as shown in the image below.
6
As you can see in the above image, the data type of ViewData Property is
ViewDataDictionary. Let’s look at the definition of the ViewDataDictionary by
right-clicking on it and selecting go to definition, and you will see the following
definition.
As you can see in the above image, the ViewDataDictionary class implements the
IDictionary. So, ViewData in ASP.NET Core MVC is a dictionary object. As a
dictionary object, it stores data in the form of Key-Value Pairs, where each key
must be a string, and the value that we pass to the dictionary will be stored as
an object type. Here, the key is of type String, and the value is of type object,
i.e., we can store any data, including null.
To use ViewData in the ASP.NET Core MVC Application, we need to set the data in
a controller by adding entries to the ViewData dictionary with a string key and
then assign some data. The key should be in string format, and you can give any
name to the key. Then, you can assign any data to this key, such as the following.
ViewData[“KeyName”] = “Some Data”;
You can access the string data from the ViewData dictionary without casting the
data to string type. But if you are accessing data other than the string type, you
must explicitly cast the data to the type you expect.
7
Example to Understand ViewData in ASP.NET Core MVC Application:
Let us see an example of using ViewData to pass data from a controller action
method to a view. In our example, we want to pass three pieces of information
from the controller action method to the view. One is the Page’s title, the second
is the page’s Header, and the third is the Student data.
namespace FirstCoreMVCWebApplication.Models
{
public class Student
{
public int StudentId { get; set; }
public string? Name { get; set; }
public string? Branch { get; set; }
public string? Section { get; set; }
public string? Gender { get; set; }
}
}
Modifying HomeController:
Next, modify the Home Controller class as shown below. Here, we remove the
existing code and add one action method, i.e., Details. As part of this method, we
create three ViewData objects to store the Title, Header, and Student data. Here,
Title, Header, and Student are the keys of the ViewData Dictionary Object.
using Microsoft.AspNetCore.Mvc;
using FirstCoreMVCWebApplication.Models;
namespace FirstCoreMVCWebApplication.Controllers
8
{
public class HomeController : Controller
{
public ViewResult Details()
{
//String string Data
ViewData["Title"] = "Student Details Page";
ViewData["Header"] = "Student Details";
Student student = new Student()
{
StudentId = 101,
Name = "James",
Branch = "CSE",
Section = "A",
Gender = "Male"
};
//storing Student Data
ViewData["Student"] = student;
return View();
}
}
}
Let us add a view named Details.cshtml within the Home folder, which is inside
the Views folder, as shown below. Once you add the Details view, your Views
folder structure should look as shown below.
Now open the Details.cshtml view and copy and paste the following code. As
you can see in the code below, we directly access the string data from the
ViewData without type casting. However, while accessing the Student data from
the ViewData, we typecast it to the appropriate Student type.
@{
Layout = null;
}
<!DOCTYPE html>
9
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewData["Title"]</title>
</head>
<body>
<h1>@ViewData["Header"]</h1>
@{
var student = ViewData["Student"] as
FirstCoreMVCWebApplication.Models.Student;
}
<div>
StudentId : @student?.StudentId
</div>
<div>
Name : @student?.Name
</div>
<div>
Branch : @student?.Branch
</div>
<div>
Section : @student?.Section
</div>
<div>
Gender : @student?.Gender
</div>
</body>
</html>
Now run the application and navigate to the “/Home/Details” URL. As shown
below, you will see the data as expected.
Type Safety: ViewData does not provide type safety as it stores data as an
object. You need to cast the data to the appropriate type when retrieving it.
10
Scope: The data in ViewData only lasts for the duration of the current HTTP
request. It’s reset for each new request, so it is not a mechanism for
persisting data between requests, such as across redirects.
Accessing Data: You can set data in a controller by adding entries to the
ViewData dictionary with a string key. In the view, you can access these
values using the same key. When used in the view, the values must be cast
to the appropriate type.
Null Handling: ViewData returns null if a key does not exist, so you should
check for null or use the ?. operator to avoid exceptions.
Usage: ViewData is best used to pass small amounts of data. If you’re
passing complex data or require type safety, consider using ViewBag or
strongly typed views.
Lightweight: ViewData is lightweight because it’s just a dictionary and
doesn’t require any extra classes or interfaces.
Dynamic: ViewData is a dynamic object, so you can use it to pass any
data.
So, we need to use ViewData when we need to pass simple or small amounts of
data that don’t justify creating a view model or when the data is temporary and
used only within the view being rendered.
In ASP.NET Core MVC, ViewBag is a dynamic object that provides a way to pass
data from the controller action method to the view. It allows us to create
properties dynamically on the fly and add properties to the ViewBag object in the
controller actions, which are then accessible in the Razor views. ViewBag is useful
for passing simple data (e.g., strings, dates) that do not require a strongly typed
view model. If you go to the Controller abstract class, you will find the following
signature of the ViewBag property.
So, in the ControllerBase class, which is the base class for controllers in ASP.NET
Core MVC, as you can see, there’s a property called ViewBag, which is a type of
DynamicViewData. This DynamicViewData is a dynamic object that allows
properties to be dynamically added at runtime.
Note: The dynamic type is introduced in C# 4.0. It is very similar to the var
keyword, which means we can store any value in it, but the type will be decided
at run time rather than compile time.
How Do We Pass and Retrieve Data from ViewBag in ASP.NET Core MVC?
11
side value, the data type will be decided at runtime. For example, if the value is a
string, the data type will be considered a string at runtime.
In a Razor view file (.cshtml), we can access the properties set in ViewBag directly
using the @ symbol followed by the property name (@ViewBag.Header ). This
dynamic access is possible because ViewBag is of type dynamic.
How to Access Data from ViewBag in ASP.NET Core MVC with String
Type:
How to Access Data from ViewBag in ASP.NET Core MVC with Complex
Type:
Since ViewBag is dynamic, accessing a property that doesn’t exist or is not set will
not throw a compile-time error. Instead, it will result in a runtime
NullReferenceException if the property is accessed without being set.
The data stored in ViewBag is available only during the current request lifecycle.
Once the view is rendered and sent to the client, ViewBag data is no longer
accessible.
Let us see an example of using ViewBag to pass data from a controller action
method to a view in the ASP.NET Core MVC Application. We will work with the
same example we worked on in our previous example with ViewData. So, modify
the Details action method of the HomeController class as shown below.
using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
12
{
public class HomeController : Controller
{
public ViewResult Details()
{
ViewBag.Title = "Student Details Page";
ViewBag.Header = "Student Details";
Student student = new Student()
{
StudentId = 101,
Name = "James",
Branch = "CSE",
Section = "A",
Gender = "Male"
};
ViewBag.Student = student;
return View();
}
}
}
As you can see in the above example, here we are using the dynamic properties
Title, Header, and Student on the ViewBag.
Now, we will see how to access the ViewBag data within a View in MVC
Application. So, modify the Details.cshtml view file as shown below. Here, you
can see we are directly accessing the string and complex type values without
typecasting, and this is possible because of the dynamic data type.
@{
Layout = null;
var student = ViewBag.Student;
}
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<h1>@ViewBag.Header</h1>
<div>
StudentId : @student?.StudentId
13
</div>
<div>
Name : @student?.Name
</div>
<div>
Branch : @student?.Branch
</div>
<div>
Section : @student?.Section
</div>
<div>
Gender : @student?.Gender
</div>
</body>
</html>
As you can see, we are accessing the data from the ViewBag using the same
dynamic properties: Title, Header, and Student. Now run the application and
navigate to the “/Home/Details” URL, and you will see the data as expected on
the webpage, as shown in the image below.
14
In ASP.NET Core MVC, both ViewBag and ViewData are mechanisms to pass data
from controllers to views, but they have some key differences in how they work
and their usage:
Type Safety:
Both ViewBag and ViewData are available during the current request. They
are typically used to pass data from controllers to views within the same
request lifecycle.
Error Handling:
ViewBag: Due to its dynamic nature, errors like null references or type
mismatches might occur at runtime if not handled carefully.
ViewData: Requires explicit casting when retrieving values, which can help
catch type mismatches earlier.
When to Use:
A Strongly Typed View in ASP.NET Core MVC is associated with a specific class,
known as a view model. This class defines the data and behaviors the View needs
to display or interact with. It is a view that expects a specific data model to be
passed to it from the controller action method.
15
As we discussed, in ASP.NET Core MVC, we can pass the model data to a view
using many different methods, such as ViewBag, ViewData, TempData, Strongly
Typed View Model, etc. The view becomes loosely typed when we pass the model
data to a View using ViewBag, TempData, or ViewData. We will not get
intellisense support or compile-time error checking in a loosely typed view. With a
Strongly Typed View, we will get the following benefits:
To create a strongly typed view in ASP.NET Core MVC, we need to follow the
below steps:
1. Create a Model: Define a model class representing the data you want to
display in the view. This class contains properties corresponding to the data
you need to access and render in the view.
2. Pass the Model to the View: In the controller action method, create an
instance of the model class, populate it with data, and then pass it to the
view.
3. Declare the Model in the View: At the top of the view file, declare the
model type using the @model directive. This informs the view about the
type of data it will be working with.
4. Access Model Properties in the View: You can access the model’s
properties inside the view using Razor syntax (@Model.PropertyName).
Here, you will get the intellisence support for the model properties.
Create a Model
First, you need to define a model class. A model is a C# class with properties. This
class will be used to transfer data between your controller and view. We will use
the same application we used in our previous two articles. So, we are going to use
the same Student model. If you are coming to this article directly without reading
our previous two articles, then please create the following Student class within
the Models folder:
namespace FirstCoreMVCWebApplication.Models
{
public class Student
{
public int StudentId { get; set; }
16
public string? Name { get; set; }
public string? Branch { get; set; }
public string? Section { get; set; }
public string? Gender { get; set; }
}
}
To create a Strongly Typed View from the controller’s action method, we must
pass the model object as a parameter to the View() extension method. The
Controller base class provides the following two overloaded versions of the View()
extension method, which we can use to pass the model object from the controller
action method to a view in the ASP.NET Core MVC Application.
Now, we will use the overloaded version of the Views() Extension method, which
takes only the model object as an input parameter. So, modify the Details action
method of the Home Controller, as shown below, to pass the student object as a
parameter to the View extension method.
using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
public class HomeController : Controller
{
public ViewResult Details()
{
//Using ViewBag
ViewBag.Title = "Student Details Page";
//Using ViewData
ViewData["Header"] = "Student Details";
//Creating Student Object to Hold Student data
Student student = new Student()
{
StudentId = 101,
Name = "James",
Branch = "CSE",
Section = "A",
Gender = "Male"
};
//Passing the Model Object as a Parameter to View Extension Method
//It means the View is going to be a Strongly Type View for the Student Model
return View(student);
17
}
}
}
Changes in Details.cshtml View:
To create a strongly typed view in the ASP.NET Core MVC Application, we need to
specify the model type within the view using the @model directive. Here, the
Student class will be our model, passed from our action method as a parameter to
the View Extension method. So, we need to specify the model for the view, as
shown below.
@model FirstCoreMVCApplication.Models.Student
Then, to access the model object properties, you can use @Model. Here, the
letter M is in uppercase. So, in our example, we can access the Student objects
properties such as Name, Gender, Branch, and Section by
using @Model.Name, @Model.Gender, @Model.Branch,
and @Model.Section, respectively. So, modify the Details.cshtml view file is
shown below to make the view a Strongly Typed View.
@{
Layout = null;
}
<!DOCTYPE html>
@model FirstCoreMVCWebApplication.Models.Student
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<h1>@ViewData["Header"]</h1>
<div>
StudentId : @Model?.StudentId
</div>
<div>
Name : @Model?.Name
</div>
<div>
Branch : @Model?.Branch
</div>
<div>
Section : @Model?.Section
18
</div>
<div>
Gender : @Model?.Gender
</div>
</body>
</html>
Now run the application and navigate to the /Home/Details URL. As shown in the
image below, you will see the data as expected.
In our example, we still use ViewBag and ViewData to pass the Header and Title
from the Controller action method to the View. Then definitely, the question that
comes to your mind is how we will pass the Header and Title to a strongly typed
view. In such scenarios, we need to use a view-specific model called View Model.
19