ASP.NET Core ViewData, BindProperty or TempData?

喜欢而已 提交于 2021-02-08 05:39:18

问题


In ASP.NET Core Views and Razor Pages we can use:

public class LoginModel
{
    [BindProperty]
    public bool DisplayCaptcha { get; set; }

    // OR

    [ViewData]
    public bool DisplayCaptcha { get; set; }

    // OR

    [TempData]
    public bool DisplayCaptcha { get; set; }
}

To share data between View/Page/Controller... But when to use each one?

In my case its a simple login page and when user set a wrong password I will display a captcha.

In the form post i'm setting a property to true (DisplayCaptcha = true) and rendering the page with the captcha:

@if (Model.DisplayCaptcha)
{            
    <div class="captcha-header">
        ...
    </div>
}

This is working fine but i'm little confuse what type the attribute should be or even if I should use any.


回答1:


ViewData should be used when data is passed from PageModel to Page.

BindProperty should be used when data is passed from PageModel to Page and vice versa via POST/GET. This is two-way binding.

TempData should be used when data should be read only once.

In your case you should use BindProperty.




回答2:


We use ViewData and TempData to maintain state of an object during postback. But because you are setting its value on every postback and it is part of model so it should be [BindProperty].



来源:https://stackoverflow.com/questions/52066526/asp-net-core-viewdata-bindproperty-or-tempdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!