Skip to main content

Difference between ViewData, ViewBag and TempData in MVC

While working with ASP.NET MVC applications one need to retain data or need to transfer data from controller to the view or one controller to another controller.
In ASP.NET MVC, there are three types of objects - ViewBag, ViewData and TempData, use to pass data from controller to view and controller to controller.
Each object has its own functionality, importance and area in which it uses and one needs to decide when to use ViewData, ViewBag or TempData. In this post we’ll look on key points of these three objects.

ViewData: ViewData helps to maintain data when you move from controller to view.

Example:
//In Controller defines ViewData FullName.
public ActionResult Index()
{
    ViewData["FullName"] = "Sandeep Kumar";
    return View();
}
//In View use ViewData
@ViewData["FullName"]

Mentioned below are some key points about ViewData:
·         ViewData is used to pass data from controller to view.
·         ViewData is a dictionary object and is of type ViewDataDictionary.
·         Just like any other dictionary object in .NET, ViewData allows you to store key-value pairs.
·         ViewData is available for the current request only
·         ViewData requires type casting for complex data type and it is recommended to check for null values to avoid error.
·         If redirection occurs, then its value becomes null.
·         ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above.
·         ViewData is faster than ViewBag.

ViewBag: ViewBag also helps to maintain data when you move from controller to view. It's a dynamic wrapper around view data.

Example:
//In Controller defines ViewBag FullName.
public ActionResult Index()
{
    ViewBag.FullName = "Sandeep Kumar";
    return View();
}
//In View use ViewBag
@ViewBag.FullName

Mentioned below are some key points about ViewBag:
·         ViewBag is also used to pass data from the controller to the view.
·         ViewBag is a dynamic wrapper around view data.
·         ViewBag takes advantage of the new dynamic features in C# 4.0.
·         ViewBag is also available for the current request only.
·         It doesn’t require typecasting for complex data type.
·         If redirection occurs, then its value becomes null.
·         ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above.
·         ViewBag is slower compare to ViewBag.

TempData: TempData helps to maintain data when you move from one controller to other controller or from one action to other action. And it helps to maintain data between redirects.

Example:
public ActionResult Index()
{
    //Set Value in TempData
    TempData["FullName"] = "Sandeep Kumar";
    return RedirectToAction("UserDetail");
}

       
public ActionResult UserDetail()
{
    //Get value from TempData.
    var name = TempData["FullName"];
    return View(name);
}

Mentioned below are some key points about ViewBag:
·         TempData helps to maintain the data when we move from one controller to another controller or from one action to another action
·         TempData is a dictionary object and is of type TempDataDictionary.
·         Just like ViewData, it also allows you to store key-value pairs.
·         TempData is only work during the current and subsequent request.
·         TempData requires type casting for complex data type and it is recommended to check for null values to avoid error.
·         TempData is used to pass data between two consecutive requests.
·         TempData is introduced in MVC1.0 and available in MVC 1.0 and above.
·         TempData internally uses session variables.
·         Though TempData used for current and subsequent request but one can persist value in TempData even after request completion. I’ve explained about this here.

Comments

Post a Comment

Popular posts from this blog

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...