Data Passing Techniques in ASP.NET Core

Data Passing Techniques in ASP.NET Core

29 Mar 2024
Intermediate
41.2K Views
19 min read

Data Passing Techniques in ASP.NET Core: An Overview

ASP.NET core techniques to transfer data from controller to view is one of the key concepts in Asp.Net Core.So that, data that 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 classes. Since in the interface, we normally use the strong type views, it is straightforward to access the object or model that needs to be passed to the controller.

You can also consider doing our ASP.NET Core Certification Training from Scholar Hat to upskill your career.

Read More: Top 50 ASP.NET Core Interview Questions and Answers

ASP.NET Core Data Passing Techniques

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

ASP.NET Core Data Passing Techniques

Read More: How can you become an ASP.NET developer

1. ViewData

View Data is one of the most common and popular techniques with the help of which we can pass the data from the controller to view. Normally, view data represents a dictionary that contains a key/value pair. View data is one of the properties of the controller which is exposed with the help of ViewDataDictionary class instances.

As per the other data-passing techniques, it is one of the fastest techniques to transfer data from the controller to view. It was the first time introduced in MVC 1.0 version and it is available in all versions from MVC 1.0. It also provides support for the previous version of Asp.Net.

In the View data, a key is a case-sensitive string value. Value can be accessed by the key name within the view data. When View data sends the data to the view, we can access the stored value within the view data by using its key.

The view data objects that store the data only exist during the current request. Once, the view is 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 the view related to this Student Data.

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

2. ViewBag

ViewBag is quite similar to ViewData. The main concept of the ViewBag is an instance of dynamic property. The ViewBag represents the dynamic data type which was first introduced in the .Net framework 4.0. So, for that reason, we can’t use these features before the .Net 4.0 version.

ViewBag can save and fetch the dictionary objects within the class dynamically. Performance-wise, the ViewBag is much slower rather than the ViewData. ViewBag was first introduced in MVC 3.0, so if anyone wants to use this, 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> 

3. TempData

TempData is one of the data passing techniques from the controller method to view. TempData always returns a data dictionary which can be derived from the TempDataDictionary class. The storing of data is just similar to the data stored in the Ajax. It works as a temporary data storage. It will keep the data at the time of the HTTP request. Temp data is most useful for transferring data between different action methods in different controllers.

In the internal mechanism, TempData uses session variables. It is mainly used for storing 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 future reference. It was also first introduced in MVC 1.0, so we can use any version of the Asp.Net Core for the use of TempData.

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 the Asp.Net core is done by using SessionState. But we can also use TempData with the implementation of cookies which can be done with the help of CookieTempDataProvider. In this case, data will be stored as a cookie in the case of TempData in the client machine. So, the end-user can view this data and modify it. But also, we can use encryption to protect this data on the client side for the safety of our application.

4. 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. The session state is stored in the client machine against any request from the client end.

Normally, session state data is 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 sending the .Net Application on each request.

Since the session state is dependent on the browser, 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. The session must contain at least one value in the session variable.

We can use the session variable for a limited period. Since we need to specify session timeout in the application it will be used its default timeout duration i.e. 20 minutes. Session data can be deleted by using 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 a part of Microsoft.AspNetCore.App meta-package. If we want to enable the session middleware, we need to implement 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();
}

5. Cookies

Cookies store the data against any request since it needs to be sent with every request. That’s why the size of the cookie is always kept as small. Today, most browsers mainly restrict the cooking up to 4096 bytes. Normally, in each server or domain, the total cookie number is always restricted and limited.

Since the cookies have a great chance of tempering 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 personalized data within the cookie.

6. Query String

This technique is 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. However, this technique is not 100% safe since access URL strings are public. So data can be manipulated during the flow at the time. It helps send 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);
}

Client to Server Data Passing

In ASP.NET core, client to server data passing, as the name suggests, means to send data from the client to the server. This can be done in many ways such as:
  1. HTTP Request Parameters- The data is passed onto the server with the help of HTTP request parameters including query string parameters for GET requests or form data for POST requests.
  2. JSON Payloads- Sometimes, the data can be sent from the client to the server in the JSON format which also provides built in support for model binding JSON data to C# objects.
  3.  HTTP Headers- Headers also provide metadata about the HTTP request so HTTP headers can pass on the data from the client to the server.
  4. Cookies- Cookies are also commonly used for storing data on the client side and send them to the server side.
  5. SignalR- It is a real time communication library which can be used both the ways, that is, from client to server as well as from server to client.

Server to Client Data Passing

The server to client data passing refers to the passing on the data from the server to the client. This can also be done in many ways such as;
  1. HTTP Response- With the help of HTTP response, data can be sent from the server to the client like HTML content, JSON data files or any type of content that be processed on the client side.
  2. View Rendering- It involves rendering of the server side views with the data provided by the server with the help of model objects like ViewBag, ViewData.
  3. JSON APIs- In this way, the data is retrieved from a database and then it is passed onto the client in JSON format.
  4. SignalR- It is a real time communication library which can be used both the ways, that is, from server to client as well as from client to server.

Cross-Page Data Passing

In ASP.NET core, the cross page data passing is a term that can be referred to the data transfer occurring between different pages or components within a web application. The different ways to that are:
  1. Query String- This method involves including the parameters to the URL as query strings to pass the data between different pages.
  2. Session State- In this, data can be stored and retrieved across multiple requests from the same user session which can be accessed afterwards from any page within the same session.
  3. Database- The data that is permanently stored on a database can be retrieved any time by different pages allowing for the sharing of the data among different users.
  4. TempData- TempData is very much like Session state but it passes data between actions during redirects.

Complex Data Passing Techniques

To pass complex data between different components or layers of an application, you can use techniques such as:
  1. Query Strings- This method involves passing the data from one page to another by adding paramaters to the URL.
  2. Server.Transfer- Through this method, the control is transferred from one page to another ASP.NET page while the original request is still there.
  3. Hidden Fields- In this, the data is passed along when the user submits a form but they can not see it is kept hidden from the user's eye.
  4. Cookies- They are used to store data on the client side but the data can only be small sized.

Best Practices and Recommendations

When you're working with ASP.NET to pass on the data which might also be complex, you need to make sure you follow best practices while doing that so that the data is safe and secure and does not affect the quality and performance in any way. Some of recommendations are as follows:
  • You should define models clearly that are strongly typed for complex data structures to reduce the occurrence of runtime errors.
  • You must validate the input data always to maintain security from injection attacks or data corruption.
  • It is advised to only pass data which is really necessary as it might increase network traffic and decrease performance.
  • While passing sensitive data, make sure that to encrypt it or transmit it over secure channels like HTTPS.
  • Avoid using excess of ViewState as it might decrease the performance if large or sensitive data is stored in it.
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.

FAQs

Q1. TempData returns which type of data?

TempData always returns a data dictionary which can be derived from the TempDataDictionary class.

Q2. What are the popular data-passing techniques in the Asp.Net Core?

ViewData, ViewBag, TempData, Session, Cookies, and Query String.

Q3. What is the ViewData technique?

ViewData represents a dictionary that contains a key/value pair. View data is one of the properties of the controller which is exposed by the help of ViewDataDictionary class instances.

Q4. How to pass data in asp net Core?

To pass data in ASP.NET core, you can use methods like model binding, TempData, ViewBag or ViewData.

Q5. How to pass data between asp net pages?

To pass data between ASP.NET pages, you can do that with the help of methods like Query Strings, Session State, Server.Transfer.

Take our free aspnet skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
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.
Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this