21
NovData Passing Techniques in ASP.NET Core
dData 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.
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 the view. It was first introduced in MVC 1.0 and 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. The value can be accessed by the key name within the view data. When the View data sends 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. Its main concept is an instance of dynamic property. The ViewBag represents the dynamic data type 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 dynamically save and fetch the dictionary objects within the class. Performance-wise, it is much slower than ViewData. ViewBag was first introduced in MVC 3.0, so anyone can create it if they want to use 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 for passing data from the controller method to the web application's view in the browser. The session state is stored on 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 use 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
- HTTP Request Parameters—The data is passed onto the server using HTTP request parameters, including query string parameters for GET requests or form data for POST requests.
- JSON Payloads—Sometimes, data can be sent from the client to the server in JSON format, which also provides built-in support for model binding JSON data to C# objects.
- HTTP Headers- Headers also provide metadata about the HTTP request so HTTP headers can pass on the data from the client to the server.
- Cookies - are also commonly used to store data on the client side and send it to the server side.
- SignalR - is a real-time communication library that can be used from client to server and from server to client.
Server to Client Data Passing
- 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.
- View Rendering—This involves rendering server-side views with the data provided by the server, using model objects like ViewBag and ViewData.
- JSON APIs- In this way, the data is retrieved from a database and then it is passed onto the client in JSON format.
- SignalR - is a real-time communication library that can be used from server to client and from client to server.
Cross-Page Data Passing
- Query String- This method involves including the parameters to the URL as query strings to pass the data between different pages.
- 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.
- 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.
- TempData- TempData is very much like Session state but it passes data between actions during redirects.
Complex Data Passing Techniques
- Query Strings- This method involves passing the data from one page to another by adding paramaters to the URL.
- Server.Transfer- Through this method, the control is transferred from one page to another ASP.NET page while the original request is still there.
- 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.
- Cookies—They are used to store data on the client side, but the data can only be small.
Best Practices and Recommendations
- To reduce the occurrence of runtime errors, you should define clearly and strongly typed models for complex data structures.
- You must validate the input data always to maintain security from injection attacks or data corruption.
- It is advised only to pass data which is really necessary as it might increase network traffic and decrease performance.
- While passing sensitive data, make sure to encrypt it or transmit it over secure channels like HTTPS.
- Avoid using an excessive amount of ViewState, as it might decrease performance if large or sensitive data is stored in it.
SUMMARY
In the above article, we discuss the different techniques for passing data 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
Take our Aspnet skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.