public class Product
{
public string Name {get; set;}
public decimal Price {get; set;}
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
}
This can be re-written as;
public class Product(string name, decimal price)
{
public string Name {get; set;} = name;
public decimal Price {get; set;} = price;
}
Seems we can save some lines with this new pattern.
To pass object from controller method to controller method use this extension methid;
public static class TempDataExtensions
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
object o;
tempData.TryGetValue(key, out o);
return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}
}
And, you can use them as follows:
Say objectA is of type ClassA. You can add this to the temp data dictionary using the above mentioned extension method like this:
TempData.Put("key", objectA);
And to retrieve it you can do this:
var value = TempData.Get<ClassA>("key") where value retrieved will be of type ClassA
On Redirect, TempData will become NULL. To solve this, try string test first;
On first controller method, set this;
TempData["error"] = "There is an error"
On a second controller method, get this;
var message = TempData["error"]
if you can see the message in second controller, no need to make any configuration changes. The problem is with your complex object serialization/deserialization
If TempData string (shown above) doesn’t work, then you need to make these configuration changes.
builder.Services.Configure<CookieTempDataProviderOptions>(options =>
{
options.Cookie.Name = "TEMPDATA";
//you have to avoid setting SameSiteMode.Strict here
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.IsEssential = true;
});
We can pass values as query string in RedirectToAction method but we don’t want to show sensitive data in URL. So the alternate is to pass it as TempData that is using session at the backend or simply use Session.
Here is a simple comparison;
Maintains data between
ViewData/ViewBag
TempData
HiddenFields
Session
ControllerToController
NO
YES
NO
YES
ControllerToView
YES
NO
NO
YES
ViewToController
NO
NO
YES
YES
If you like to store/retrieve complex objects between controllers using TempData, use this extension method;