dmsokol13
dmsokol13

Reputation: 17

Page Model Bool always returns false

I'm working on a razor pages project and I'm having an issue changing the value of my page model when clicking a button. It should toggle the value of IsCreatingCompany with each click. Here is my code:

            <div class="col-6 text-end">
                <form asp-page-handler="ToggleCreateCompany" method="post">
                    <button class="btn btn-primary" name="CreateCompanyResult" [email protected]>Add Company</button>
                </form>
            </div>
            @if (Model.IsCreatingCompany)
            {
                <label>is true</label>
            }
            else
            {
                <label>is false</label>
            }
        public IActionResult OnPostToggleCreateCompany(bool CreateCompanyResult)
        {
            IsCreatingCompany = !CreateCompanyResult;
            return Page();
        }

I have a feeling I'm making a small error somewhere, or misunderstanding something. Some things I've tried:

  1. Swapping name and value field order (I read somewhere that could work).
  2. Changing OnPost method to void return.
  3. Making name of input parameter match field name of IsCreatingCompany.

Things I've verified are working:

  1. Clicking the button does enter the OnPostToggleCreateCompany method.
  2. When the page is first loaded and OnGet is called, the value initializes to false. Also, I do not initialize it in the constructor.
  3. After the first click, the value updates to true, but the value in my model is still false.
  4. All additional clicks leave "true" on the page and "false" in the model, rather than toggling the value

Please let me know if I need to post any additional code and Thanks for any help!!!

Upvotes: 0

Views: 575

Answers (1)

Yiyi You
Yiyi You

Reputation: 18199

Try to use @Model.IsCreatingCompany.ToString() to replace @Model.IsCreatingCompany,so that the data passed to handler will be correct,here is a demo:

cshtml:

<div class="col-6 text-end">
                <form asp-page-handler="ToggleCreateCompany" method="post">
                    <button class="btn btn-primary" name="CreateCompanyResult" [email protected]()>Add Company</button>
                </form>
            </div>
            @if (Model.IsCreatingCompany)
            {
                <label>is true</label>
            }
            else
            {
                <label>is false</label>
            }

Upvotes: 1

Related Questions