Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TempData null in asp.net core

I am trying to use TempData in asp.net core However I am getting a null value on the get method of TempData. Can anyone please let me know how can I use TempData in asp.net core

Below are the things I, have added as per the research.

Project.json file

{   "dependencies": {     "Microsoft.NETCore.App": {       "version": "1.0.1",       "type": "platform"     },     "Microsoft.AspNetCore.Mvc": "1.0.1",     "Microsoft.AspNetCore.Routing": "1.0.1",     "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",     "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",     "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",     "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",     "Microsoft.Extensions.Configuration.Json": "1.0.0",     "Microsoft.Extensions.Logging": "1.1.0",     "Microsoft.Extensions.Logging.Console": "1.0.0",     "Microsoft.Extensions.Logging.Debug": "1.0.0",     "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",     "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",     "Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",     "Microsoft.EntityFrameworkCore.Design": "1.1.0",     "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",     "DataBase": "1.0.0-*",     "UnitOfWork": "1.0.0-*",     "ViewModel": "1.0.0-*",     "Common": "1.0.0-*",     "System.IdentityModel.Tokens.Jwt": "5.0.0",     "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",     "Microsoft.AspNetCore.Diagnostics": "1.0.0",     "Microsoft.AspNetCore.StaticFiles": "1.0.0",     "Microsoft.AspNetCore.Session": "1.1.0",     "Microsoft.Extensions.Caching.Memory": "1.1.0"   },    "tools": {     "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",     "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final",     "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final"   },    "frameworks": {     "netcoreapp1.0": {       "imports": [         "dotnet5.6",         "portable-net45+win8"       ]     }   },    "buildOptions": {     "emitEntryPoint": true,     "preserveCompilationContext": true   },    "runtimeOptions": {     "configProperties": {       "System.GC.Server": true     }   },    "publishOptions": {     "include": [       "wwwroot",       "**/*.cshtml",       "appsettings.json",       "web.config"     ]   },    "scripts": {     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]   } } 

start.cs file

public void ConfigureServices(IServiceCollection services) {     services.AddMemoryCache();     services.AddSession();     // Add framework services.     services.AddMvc();     services.AddTransient<IMarketUOW, MarketUow>();     services.AddTransient<ICategoryUow, CategoryUow>();     services.AddTransient<IUserProfileUow, UserProfileUow>();     services.AddTransient<IItemUow, ItemUow>();      services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));     var connection = Configuration.GetConnectionString("DefaultConnection");     services.AddDbContext<EmakitiContext>(options => options.UseSqlServer(connection)); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {     app.UseSession();     app.UseMvc(routes =>     {         routes.MapRoute(             name: "default",             template: "{controller=Home}/{action=Index}/{id?}");         });     } 

Here is the implementation of tempdata.When this method is called I can see the value in TempData.

[HttpGet("{pageNumber}")] public GenericResponseObject<List<MarketViewModel>> GetMarketList(int pageNumber) {     TempData["Currentpage"] = pageNumber;     TempData.Keep("Currentpage");     GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>();     genericResponseObject.IsSuccess = false;     genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed;     try     {         var marketItem = _iMarketUow.GetMarketList(pageNumber);         genericResponseObject.Data = marketItem.Item1;         var totalPages = (int)Math.Ceiling((decimal)marketItem.Item2 / (decimal)10);         genericResponseObject.TotalPage = totalPages;         genericResponseObject.IsSuccess = true;         genericResponseObject.Message = ConstaintStingValue.Tag_SuccessMessageRecord;         genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionSuccess;     }     catch (Exception exception)     {         genericResponseObject.IsSuccess = false;         genericResponseObject.Message = exception.Message;         genericResponseObject.ErrorCode = exception.HResult;         genericResponseObject.ExceptionErrorMessage = exception.StackTrace;     }     return genericResponseObject; } 

But the below method has null value in the temp data.

[HttpPost] public GenericResponseObject<List<MarketViewModel>> AddUpdateMarket([FromBody] MarketViewModel marketViewModel) {     GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>();     genericResponseObject.IsSuccess = false;     genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed;      if (marketViewModel!= null && ModelState.IsValid)     {         try         {             _iMarketUow.AddUpdateMarketList(marketViewModel);             genericResponseObject = GetMarketList(Convert.ToInt16(TempData.Peek("Currentpage")));         }         catch (Exception exception)         {             genericResponseObject.IsSuccess = false;             genericResponseObject.Message = exception.Message;             genericResponseObject.ErrorCode = exception.HResult;             genericResponseObject.ExceptionErrorMessage = exception.StackTrace;         }     }     else     {         genericResponseObject.Message = ConstaintStingValue.Tag_InputDataFormatNotMatch;     }     return genericResponseObject; } 

Here is the image of the debug session

first request of http which hold the value to the tempdata

null value on the second request

like image 331
San Jaisy Avatar asked Jan 19 '17 04:01

San Jaisy


People also ask

Can we use TempData in .NET core?

TempData in MVC is used to pass data from Controller to Controller or Controller to view and it is used to pass data that persists only from one request to the next. TempData requires Typecasting. And also check for Null value before reading the value from it.

What is TempData in asp net core?

TempData. ASP.NET Core exposes the Razor Pages TempData or Controller TempData. This property stores data until it's read in another request. The Keep(String) and Peek(string) methods can be used to examine the data without deletion at the end of the request.

How do I show TempData values in view?

Passing the data from Controller to View using TempDataGo to File then New and select “Project” option. Then create the ASP.NET web application project as depicted below. Then select “Empty” and tick “MVC” then click OK.

Can we use TempData in view?

TempData is a property in the ControllerBase class. So, it is available in any controller or view in the ASP.NET MVC application. The following example shows how to transfer data from one action method to another using TempData.


1 Answers

Edited:

As Described in https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.2#tempdata-provider-and-session-state-cookies-arent-essential by default TempData cookies are removed by the CookiePolicy Middleware. this can be changed by putting this in Startup.ConfigureServices():

// The TempData provider cookie is not essential. Make it essential // so TempData is functional when tracking is disabled. services.Configure<CookieTempDataProviderOptions>(options => {     options.Cookie.IsEssential = true; });  

=============================================

Old Answer:

After Migrating to ASP Core 2.1 I had this issue and after working for a day find the solution:

in Startup.Configure() app.UseCookiePolicy(); should be after app.UseMVC();

like image 166
HamedH Avatar answered Oct 12 '22 04:10

HamedH