Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core ViewData, BindProperty or TempData?

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.

like image 328
Vanderlei Pires Avatar asked Oct 15 '25 20:10

Vanderlei Pires


1 Answers

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.

like image 100
Pavel Levchuk Avatar answered Oct 18 '25 14:10

Pavel Levchuk