为什么TempData将long []转换为int []

时间:2018-12-06 03:30:49

标签: c# razor asp.net-core

ModelView ...

public class FieldIndexViewModel
{
    //Field Field { get; set; } //maybe?
    public long Id { get; set; }

在我的c#控制器中,我有一个“ Id”,其键入为long。一切都很好。

        // store our fieldlist ids for prev and next iterations
        long[] tempData = FieldIndexViewModels.Select(s => s.Id).ToArray();
        TempData["FieldList"] = tempData;

        return View(FieldIndexViewModels);
    }

在我的get方法中,FieldList更改为int,因此以下操作因谓词错误而失败。原始数据显示这些现在为int/int32

    // GET: Fields/Edit/5
    [Authorize]
    public async Task<IActionResult> Edit(long? id, int? tn, int? workPy)
    {
        // grab field list from tempdata
        List<long> FieldList = new List<long>();
        if (TempData.ContainsKey("FieldList"))
        {
            long[] ids = (long[])TempData["FieldList"];

            List<long> temp = ids.ToList(); ;

            FieldList.AddRange(temp);
        }

为什么TempData会在哪里更改这些内容?这些在原始方法存在之前的原始数据中显示的时间很长。

enter image description here

enter image description here

enter image description here

相同的类...除了在第315行上没有被覆盖之外,现在不被覆盖,因此我现在可以继续编码(只是将int32强制转换为long)

enter image description here

****全新的ASP核心WebApp **** 同样的问题?!​​?

enter image description here

1 个答案:

答案 0 :(得分:2)

TempData在ASP.NET Core中是默认设置,它作为BSON序列化到cookie中。

不幸的是,将long[]作为BSON(或JSON)存储不会记住类型-因此,一个long型数组和一个int型数组看起来完全一样。不幸的是,反序列化的机制是imperfect,用于确定反序列化为的类型。

因此,最好的选择可能是使用自定义类型的数组(例如,具有公共Bob属性的long)。然后将数组序列化/编码为JSON字符串,然后将该字符串存储在TempData中(在这种情况下,它将是BSON编码的JSON!)。 在读取路径上,您显然需要先对string中的TempData进行JSON解码,然后再使用它。

相关问题