ASP.NET Core Razor Pages - checkbox asp-for

Joyce 0 Reputation points
2024-07-24T06:28:45.1566667+00:00

Hello,

New user here, a beginner trying to understand how checkbox asp-for works.

In this sample application, I am trying to toggle a checkbox on post by a button, but failing.

Having googled, read tutorials and attempted variations, I am still stuck.

Index.cshtml

@page
@model IndexModel
@{
	ViewData["Title"] = "Home page";
}
<form method="post">
	<input id="checkbox" asp-for="IsChecked" />
	<label for="checkbox">asp-for = "IsChecked"</label>
	<br />
	<br />
	<span>Model.IsChecked = @Model.IsChecked</span>
	<br />
	<br />
	<input type="submit" value="IsChecked = !IsChecked" />
</form>

Index.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication1.Pages
{
	public class IndexModel : PageModel
	{
		[BindProperty]
		public bool IsChecked { get; set; }

		public void OnPost()
		{
			IsChecked = !IsChecked;
		}
	}
}

Auto-generated

<input id="checkbox" type="checkbox" data-val="true" data-val-required="The IsChecked field is required." name="IsChecked" value="true">

<input name="IsChecked" type="hidden" value="false">

Issue:

When launched, checkbox is not checked and span shows False, as expected.

1

On submit the first time, span changes to True, hence OnPost works, yet checkbox remains unchecked.

2

On further submits, span remains True and checkbox remains unchecked.

Question:

Why is checkbox never checked despite being bound to Model.IsChecked which OnPost successfully toggled to True as span shows? Sticking to using tag helpers, what am I missing to make it work?

Thanks in advance for any advice or direction.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,397 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ping Ni-MSFT 3,455 Reputation points Microsoft Vendor
    2024-07-24T08:09:51.67+00:00

    Hi @Joyce,

    Default Tag Helper displays ModelState value instead of Model. Just add ModelState.Clear() before you return the Page:

    public void OnPost()
    {
        //just be sure clear the ModelState before page rendering
    	IsChecked = !IsChecked;
    	ModelState.Clear();
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful