问题描述
在ASP.NET Core视图和Razor页面中,我们可以使用:
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.
在表单发布中,我将属性设置为true( DisplayCaptcha = true
),并使用验证码呈现页面:
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.
推荐答案
ViewData
.
BindProperty
(反之亦然).这是双向绑定.
BindProperty
should be used when data is passed from PageModel to Page and vice versa via POST/GET. This is two-way binding.
TempData
应该在数据只能读取一次时使用.
TempData
should be used when data should be read only once.
在您的情况下,您应该使用 BindProperty
.
In your case you should use BindProperty
.
这篇关于ASP.NET Core ViewData,BindProperty还是TempData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!