You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TempData中存储与读取decimal类型数据?

解决TempData无法存储decimal类型的问题

ASP.NET Core默认的DefaultTempDataSerializer不支持直接序列化System.Decimal类型,直接存储decimal会触发你遇到的序列化错误,下面是两种实用的解决方法:

方法一:转字符串存取(最简单直接)

把decimal转成字符串存储,读取时再解析回decimal,建议用固定文化格式避免不同地区的格式差异导致解析失败:

存储代码

// 使用InvariantCulture确保格式统一
TempData["PromocodeDiscount"] = 5.00m.ToString(System.Globalization.CultureInfo.InvariantCulture);

读取代码

decimal discount = 0;
// 先判断类型再解析,避免空引用或类型转换错误
if (TempData["PromocodeDiscount"] is string discountStr)
{
    decimal.TryParse(discountStr, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out discount);
}

方法二:用自定义类包装(适合复杂场景)

如果需要存储多个和折扣相关的值,或者想保持类型安全,可以把decimal包装在一个简单的POCO类里:

定义包装类

public class DiscountInfo
{
    public decimal DiscountValue { get; set; }
}

存储代码

TempData["PromocodeDiscount"] = new DiscountInfo { DiscountValue = 5.00m };

读取代码

decimal discount = 0;
if (TempData["PromocodeDiscount"] is DiscountInfo discountInfo)
{
    discount = discountInfo.DiscountValue;
}

注意:自定义类需要是公共类,属性为可读写的,默认序列化器能正常处理这类简单对象。

内容的提问来源于stack exchange,提问作者Alice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 05:22:07