Home > Software design >  Page Model Bool always returns false
Page Model Bool always returns false

Time:05-24

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 >
                <form asp-page-handler="ToggleCreateCompany" method="post">
                    <button  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!!!

CodePudding user response:

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 >
                <form asp-page-handler="ToggleCreateCompany" method="post">
                    <button  name="CreateCompanyResult" [email protected]()>Add Company</button>
                </form>
            </div>
            @if (Model.IsCreatingCompany)
            {
                <label>is true</label>
            }
            else
            {
                <label>is false</label>
            }
  • Related