Reputation: 2360
I am doing an Asp.Net Core MVC6 App.
I am using TempData to use it from the View
I am using like this.
private async void CreateClaimsByUserRole(string role, string usertType)
{
List<string> permission = await _iUIConfig.CreateClaimsByUserRole(role, usertType);
TempData["MyList"] = permission;
TempData.Keep();
}
I am saving a List<string>
Here is some other functions
public async Task<List<string>> CreateClaimsByUserRole(string role, string usertType)
{
List<RolesAccessModel>? oResponse = await GetRolesPerApplication();
List<string> permissions = TransformRowsIntoPermissions(oResponse,role, usertType);
return permissions;
}
And
private List<string> TransformRowsIntoPermissions(List<RolesAccessModel>? rows, string role, string usertType)
{
List<string> permissionList = new();
if(rows!=null)
{
foreach (RolesAccessModel row in rows)
{
if (row.Roles!=string.Empty && row.Roles != null && !row.Roles.Contains(role))
continue;
if (row.UserType != string.Empty && row.UserType != null && !row.UserType.Contains(usertType))
continue;
// if we hget here we have a match
if (!permissionList.Contains(row.EventName))
permissionList.Add(row.EventName);
}
}
return permissionList;
}
As it says here
I can do this in the same Method and works fine..
List<string> SomeList = TempData["MyList"] as List<string>;
But if I want to retrieve the data in another Method, It is null..
The only way to retrieve data is using
var SomeList = TempData["MyList"] ;
I need to retrieve the data from the View, I have the same problem
@if (TempData["Claims"] != null)
{
var claims = TempData["MyList"] as List<string>;
@foreach (string permission in claims)
{
<p>@permission</p>
}
}
Where var claims = TempData["MyList"] as List<string>
; is null
Reading this page, I also add in Program.cs
builder.Services.Configure<CookieTempDataProviderOptions>(options => {
options.Cookie.IsEssential = true;
});
But still does not work.
What I am missing?
Thanks
Upvotes: 0
Views: 386
Reputation: 11546
It was related a serialize/deserialize issue,If you are not trying with simple types,I recomand you to serialize it before adding it to the dictionary
If you try as below :
List<decimal> strlist = new List<decimal> { 1, 2, 3 };
TempData["SomeList"] = strlist;
You would got an error:
It indicates your TempDataDictionary would be serialized before appended to cookie
For Complex types, you could try as below:
List<string> strlist = new List<string> { "q", "w", "e" };
var jsonstr= JsonSerializer.Serialize(strlist);
TempData["SomeList2"] = jsonstr;
deserialize:
var tempobj2 = TempData["SomeList2"];
var list = JsonSerializer.Deserialize<List<string>>(tempobj2 as string);
and You could cast the value to string[] indicates it was serialized/deserialized like below:
List<string> strlist = new List<string> { "q", "w", "e" };
var jsonStr= JsonSerializer.Serialize(strlist);
var obj = JsonSerializer.Deserialize<string[]>(jsonStr) as object;
Upvotes: 1