【问题标题】:Storing list in TempData throwing exception在 TempData 中存储列表引发异常
【发布时间】:2018-09-12 06:50:02
【问题描述】:

我正在尝试在 .net core 2.1 的 TempData 中存储一个列表。问题是它在将列表存储在 tempdata 中时没有给出任何错误,但在 return 语句之后,它总是抛出异常并将我抛出到 ajax 调用的错误部分。在 ajax 调用中调试错误消息时,它只是说“错误” 这是控制器代码:

 IList<Product> productList = new List<Product>
 {
     new Product{ProductId=Guid.NewGuid().ToString(),Name="142525"},
     new Product{ProductId=Guid.NewGuid().ToString(),Name="122555"},
     new Product{ProductId=Guid.NewGuid().ToString(),Name="125255"}
 };

 TempData["Products"] = productList;
 return Json(productList);

Ajax 请求:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: '@Url.Action("Index", "Product")',
        success: function (result) {
             alert('All ok');
        },
        error: function (result, err) {
            debugger;
            alert('Something went wrong');
        }
    }); 
}); 

这里是启动文件代码:

 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
 services.AddSession();

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseCookiePolicy();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    }); 

我也尝试在 app.UseMvc 之后移动 app.UseCookiePolicy,但仍然没有运气。这是微软官方文档链接https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#tempdata,我已经尝试了这里提到的所有内容。我做错了什么?

【问题讨论】:

  • 与我们分享 ajax 请求。
  • 我已经更新了我的问题并添加了 ajax 请求

标签: asp.net-core asp.net-core-2.0


【解决方案1】:

您的问题是由 TempData 不支持复杂类型引起的。

您可以尝试将对象序列化为字符串并将其保存在TempData 中。

TempData["Products"] = JsonConvert.SerializeObject(productList);

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2014-12-23
    • 2021-12-12
    相关资源
    最近更新 更多