将复杂对象存储在TempData中 [英] Store complex object in TempData
问题描述
我一直试图通过使用TempData来将数据传递给重定向后的操作,如下所示:
I've been trying to pass data to an action after a redirect by using TempData like so:
if (!ModelState.IsValid)
{
TempData["ErrorMessages"] = ModelState;
return RedirectToAction("Product", "ProductDetails", new { code = model.ProductCode });
}
但不幸的是,它失败并显示以下消息:
but unfortunately it's failing with the following message:
'
System.InvalidOperationException
Microsoft.AspNet.Mvc.SessionStateTempDataProvider'
无法序列化 类型为'ModelStateDictionary'
的会话状态的对象.'
'
System.InvalidOperationException
TheMicrosoft.AspNet.Mvc.SessionStateTempDataProvider'
cannot serialize an object of type'ModelStateDictionary'
to session state.'
我在 Github中的MVC项目中发现了一个问题,但是解释了为什么我会收到此错误,但我看不出有什么可行的选择.
I've found an issue in the MVC project in Github, but while it explains why I'm getting this error, I can't see what would be a viable alternative.
一种选择是将对象序列化为json字符串,然后反序列化并重建ModelState
.这是最好的方法吗?我是否需要考虑任何潜在的性能问题?
One option would be to serialize the object to a json string and then deserialize it back and reconstruct the ModelState
. Is this the best approach? Are there any potential performance issues I need to take into account?
最后,对于序列化复杂对象或使用不涉及使用TempData
的其他模式,是否有其他选择?
And finally, are there any alternatives for either serializing complex object or using some other pattern that doesn't involve using TempData
?
推荐答案
您可以创建如下扩展方法:
You can create the extension methods like this:
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:
说objectA
是ClassA
类型.您可以使用上述扩展方法将其添加到临时数据字典中,如下所示:
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")
检索到的value
的类型将为ClassA
var value = TempData.Get<ClassA>("key")
where value
retrieved will be of type ClassA
这篇关于将复杂对象存储在TempData中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!