Data Passing Techniques in ASP.NET Core

23 Oct 2023
Intermediate
38.1K Views
12 min read  

In Asp.Net Core one of the key concepts is to pass the data from the controller method to the view. So that, data which we can fetch from the database or storage can be shown in the interface which is normally known as views. So in the Asp.Net Core, the best and popular method to pass the data to the view from the controller is through the help of model classes which are normally known as view class. Since in the interface, we normally use the strongly type views, so it is very much easy to access the object or model which need to pass the controller. You can also consider doing our ASP.NET Core Certification Training from Dot Net Tricks to upskill your career.

ASP.NET CORE DATA PASSING TECHNIQUES

In Asp.Net Core, we can perform this operation with the help of the different type of data passing techniques. In this section, we will discuss some of the most important and popular data passing techniques in the Asp.Net Core.

ASP.NET CORE DATA PASSING TECHNIQUES

ViewData

View Data is one of the most common and popular technique with the help of which we can pass the data from the controller to view. Normally, view data is actually representing a dictionary which contains a key/value pair. View data is one of the properties of the controller which is exposed by the help ViewDataDictionary class instances. As per the other data passing techniques, it is one of the fastest technique to transfer data from the controller to view. It is first time introduced in MVC 1.0 version and it is available in all version from MVC 1.0. It also provides support in the previous version of Asp.Net.

In the View data, a key is basically a case-sensitive string value. Value can be accessed by the key name within the view data. When View data send the data to the view, we can access the stored value within the view data by using its key. The view data objects which stored the data only exists during the current request. Once, the view generated in the browser and it sends the data back to the server from the client, the ViewData object is automatically destroyed and cleared. The below code demonstrates the controller method of StudentIndex which will return the view along with data.

public ActionResult StudentIndex() 
{ 
 List<string>lstStudent = new List<string>(); 
 lstStudent.Add("Debasis"); 
 lstStudent.Add("Samrat"); 
 lstStudent.Add("Rahul"); 
 ViewData["StudentData"] = lstStudent; 
 return View(); 
} 

Now, the below code demonstrates how to populate view related to this Student Data.

 
<ul> 
@foreach (var data in ViewData["StudentData"] as List<string>) 
{ 
<li>@data</li> 
}
</ul>

ViewBag

View Bag is quite similar to the ViewData. The main concept of the view bag is an instance of dynamic property. Basically, the view bag is representing the dynamic data type which is first introduced in the .Net framework 4.0. So, for that reason, we can’t use these feature before the .Net 4.0 version. View bag can save and fetch the dictionary objects within the class dynamically. View bag is always returned a strongly typed object. Performance-wise, View bag is much slower rather than the ViewData. View Bag is first time introduced in the MVC 3.0, so if anyone wants to use this then they can create it.

 
public ActionResult Index() 
{ 
 List<string> lstStudent = new List<string>(); 
 lstStudent.Add("Debasis"); 
 lstStudent.Add("Samrat"); 
 lstStudent.Add("Rahul"); 
 ViewBag.StudentData = Student; 
 return View(); 
} 

<ul> 
@foreach (var student in ViewBag.StudentData) 
{ 
<li>@student</li> 
}
</ul>
 

TempData

Temp data is one of another data passing techniques from the controller method to view. Actually, temp data always return a data dictionary so that which can be derived from TempDataDctopmary class. The storing of data is just similar to the data storing in the Ajax. Actually, it is worked as a temporary data storage. It will keep the data at the time of the HTTP request. Temp data is most useful to transfer data between different action method in the different controller. In the internal mechanism, temp data is basically used session variables. It is mainly used for store data as a one time message. If we want to keep the tempdata source after the view is rendered, then we need to use the TempData.Keep() method so that we can keep the value of the temp data for the future reference. It is also first introduced in MVC 1.0, so we can use any version of the Asp.Net Core for the use of Temp Data.

 
public ActionResult Index() 
{ 
 List<string> lstStudent = new List<string>(); 
 lstStudent.Add("Debasis"); 
 lstStudent.Add("Samrat"); 
 lstStudent.Add("Rahul"); 
 TempData["StudentData"] = Student; 
 return View(); 
} 

For the above incident with Formerly, we will provide a custom definition of the master.

 
<ul> 
 @foreach (var data in TempData["StudentData"] as List<string>) 
 { 
 <li>@data</li> 
 }; 
</ul>

In the case of Tempdata, the default implementation in Asp.Net core is done by using SessionState. But we can also use tempdata with the implementation of cookie which can be done with the help of CookieTempDataProvider. In this case, data will be stored as a cookie in case of tempdata in the client machine. So, the end-user can view this data and modify it. But also, we can use encryption for protecting this data in the client side for the safety of our application.

Session

Session State is one of the best data passing techniques to pass data from the controller method to the view of the web application in the browser. Session state stored in the client machine against any request from the client end. Normally, session state data stored in the client machine with the help of cookies. Asp.net Core perpetually maintained the session state by adding a change of state to the consumer machine that principally contains a session Id which requires to send the .net application on each request. Since the session state is totally dependent on the browser, so we can’t share the session state values across the browsers. If a cookie completes its lifespan, then a new session along with the new cookie has been created. We can’t create an empty session. Session must be contained at least one value in the session variable. We can use the session variable for a limited time of period. Since we need to specify session timeout in the application or it will be used its default timeout duration i.e. 20 minutes. Session data can be deleted by use ISession.Clear method implementation or when it will expire due to timeout.

Session objects can be configured in our application with the help of Microsoft.AspNetCore.Session package which is basically is a part of Microsoft.AspNetCore.App meta-package. If we want to enable the session middleware, then we need to implement the Microsoft.AspNetCore.Session package in the StartUp.cs class. We need to change the ConfigureServices(IServiceCollection objService) method in the StartUp.cs class to add the AddDistributedMemoryCache() and AddSession() method in the ConfigureServices().

 
objService.AddDistributedMemoryCache();
objService.AddSession();

Now, we need to inform the Asp.Net Core to use a Memory Cache to store the session data.

 
public void Configure(IApplicationBuilder appInfo, IHostingEnvironment envInfo)
{
appInfo.UseHttpsRedirection();
appInfo.UseStaticFiles();
appInfo.UseCookiePolicy();
appInfo.UseSession();
appInfo.UseHttpContextItemsMiddleware();
appInfo.UseMvc();
}

Cookies

One of the most important data passing techniques is Cookies. Basically, cookies store the data against any request since it needs to be sent with every request. That’s why the size of the cookie always kept as small. Today, most of the browser mainly restrict the cooking up to 4096 bytes. Normally, in each server or domain, total cookie number is always been restricted and limited. Since the cookies have a great chance of tempering of data. For this reason, we need to validate the cookies by the mobile application. We can configure the cookie is such a way that it can be expired into the client master. The end-user can delete the cookie from the client machine. Normally, in the web application, we use the cookie for storing the user-specific personalize data within the cookie.

Query String

In Asp.Net Core, the Query string is known as other data passing techniques. This technique normally used to pass some from the view engine to the controller using the access URL. But it can accept only some limited amount of data which can be passed from one request to another request. But this technique is not 100% safe since access URL strings are public. So data can be manipulated during the flow at the time. It is helpful for sending some information to the server-side i.e. controller from the view engine as a URL string.

 
@Html.ActionLink("Pass Data", "Index", new { Code = 100, Name = “Debasis”, Department = "Software" })

Now, in the controller, we need to create an action method as below to receive this information:

 
public ActionResult Index(int code, string strName, string strDepartment)
{
string strResult = “Id =” + code.ToString() + “ Name=” + strName + “ Department=” + strDepartment;
return Content(strResult);
}
SUMMARY

So, in the above article, we discuss the different techniques about data passing process from the controller or server-side to the client-side or view. Check out our free ASP.NET Core Course Online to get an edge over the competition.

About Author
Debasis Saha (Technical Manager, Author and Mentor)

He is an ASP.Net, MVC and Angular Technical Manager with 10 years of experience. He always been a great fan of Microsoft Technologies and loves working on them. He has expertise in Asp.Net, MVC, SQL Server, MongoDB, Angular JS, and Angular. He loves to write articles about these technologies.
Learn to Crack Your Technical Interview

Accept cookies & close this