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:
- Swapping name and value field order (I read somewhere that could work).
- Changing OnPost method to void return.
- Making name of input parameter match field name of IsCreatingCompany.
Things I've verified are working:
- Clicking the button does enter the OnPostToggleCreateCompany method.
- When the page is first loaded and OnGet is called, the value initializes to false. Also, I do not initialize it in the constructor.
- After the first click, the value updates to true, but the value in my model is still false.
- 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>
}