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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With