Is there a way to access a complex model property of a page handler in the Razor page?

Viewed 31

I have a page handler that has a complex property for model binding. I want to access the property to the razor page so I can use the tag helpers to generate the form inputs from the property.

This is my page handler:

public async Task<IActionResult> OnPostChangePassword(PasswordChangeInput Input)
{
     // Some code

}

I want to access the property so I can use it with asp-for

@page
@model EditPasswordModel
@
{
    //Some code
}

<form method="post">
    <div class="flex justify-between my-1">
        <label class="text-gray-700" for="cus_name">Password:</label>
        <input asp-for="Input.Password" class="px-3 py-1 text-gray-900" />
    </div>
    <div class="flex justify-between my-1">
        <label class="text-gray-700" for="cus_name">Confirm Password:</label>
        <input asp-for="Input.ConfirmPassword" class="px-3 py-1 text-gray-900" />
    </div>
    <div>
        <input type="submit" />
    </div>
</form>
1 Answers

In your PageModel class you need to add a PasswordChangeInput property with [BindProperty] attribute.

public class EditPasswordModel : PageModel
{
    [BindProperty]
    public PasswordChangeInput Input { get; set; }

    public async Task<IActionResult> OnPostChangePassword()
    {
        // Input property will be populated from form
    }
}

And you also need to add asp-page-handler attribute to your form:

<form method="post" asp-page-handler="ChangePassword">
    ...
</form>

Edit:

If you don't want to add the property to the PageModel you can pass it as parameter to the OnPostChangePassword handler:

public class EditPasswordModel : PageModel
{
    public async Task<IActionResult> OnPostChangePassword(PasswordChangeInput Input)
    {
        // Some code
    }
}

BUT now you won't be able to use input tag helpers to create the form using asp-for="Input.Password". You must add the correct name attribute to the inputs manually:

<form method="post" asp-page-handler="ChangePassword">
    <div class="flex justify-between my-1">
        <label class="text-gray-700" for="cus_name">Password:</label>
        <input name="Input.Password" class="px-3 py-1 text-gray-900" />
    </div>
    <div class="flex justify-between my-1">
        <label class="text-gray-700" for="cus_name">Confirm Password:</label>
        <input name="Input.ConfirmPassword" class="px-3 py-1 text-gray-900" />
    </div>
    <div>
        <input type="submit" />
    </div>
</form>

https://www.learnrazorpages.com/razor-pages/model-binding#binding-complex-objects

Related