【问题标题】:Why tempdata attribute retain after first read?为什么 tempdata 属性在第一次读取后保留?
【发布时间】:2020-07-10 22:24:54
【问题描述】:

它假设 tempdata 读取一次并被处理,并且在使用它作为属性之前没问题,现在使用它就像属性一样,它在第一次读取后保留到下一个请求 这是我的示例代码 页面A

public class AModel : PageModel
    {
        [TempData]
        public string Message { get; set; }
        public void OnGet()
        {
            Message = "test Page A";
        }
    }

<h1>A</h1>
    
<p>@Model.Message</p>

<a asp-page="b">Page B</a>

页面 B

    public class BModel : PageModel
{
    [TempData]
    public string Message { get; set; }

    public void OnGet()
    {
    }
}

<h1>B</h1>

<p>@Model.Message</p>

<a asp-page="A">Page A</a>

当从页面 A 导航到页面 b 时,它不应该显示来自页面 A 的消息,但我得到消息出现在页面 B 中,结果看起来像这样

B 测试页A

页面A

【问题讨论】:

    标签: asp.net-core razor-pages tempdata


    【解决方案1】:

    当从页面 A 导航到页面 b 时,它不应该显示来自页面 A 的消息

    如果你用下面的代码做一个测试,你会很容易发现A.cshtml中的代码sn -p @Model.Message不读取TempData值。

    <h1>A</h1>
    
    using TempData["Message"]: <p>@TempData["Message"]</p>
    <hr />
    using Model.Message: <p>@Model.Message</p>
    <hr />
    using TempData.Peek("Message"): <p>@TempData.Peek("Message")</p>
    <hr />
    using Model.Message: <p>@Model.Message</p>
    
    <a asp-page="b">Page B</a>
    

    以上测试的输出

    正如 this doc 中提到的关于 TempData:

    This property stores data until it's read in another request.
    

    【讨论】:

    • 请注意“存储数据直到在另一个请求中读取”。
    • 在使用 tempdata[message] 和给属性消息属性 tempdata 之间是否存在差异,第一个工作正常,不在页面 B 中显示第二个在页面 a 和 b 中显示
    • 如果你比较cookie(或set-cookie头),你会发现tempdata相关的cookie.AspNetCore.Mvc.CookieTempDataProvider是没有值like this,而在A.cshtml中使用@TempData["message"]来访问值,因此该值未显示在页面 B 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    相关资源
    最近更新 更多