在 TempData 中存储复杂对象 [英] Store complex object in TempData

查看:35
本文介绍了在 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.InvalidOperationExceptionMicrosoft.AspNet.Mvc.SessionStateTempDataProvider' 无法序列化'ModelStateDictionary' 类型的对象到会话状态.'

'System.InvalidOperationException The Microsoft.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:

objectAClassA 类型.您可以使用上述扩展方法将其添加到临时数据字典中,如下所示:

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("key")其中检索到的 value 将是 ClassA

var value = TempData.Get<ClassA>("key") where value retrieved will be of type ClassA

这篇关于在 TempData 中存储复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆