Thanks in advance for any help
I am working in aspnet core 2.1 razor pages. I need to repopulate form data when validation fails or ModelState is Invalid.
In MVC, we can use return View(model)
but how to do that in aspnet core 2.1 razor page.
I tried return Page()
, but that fires server side validation but does not repopulate data in form
Need Help...
Repopulation of the form values occurs automatically if you
[BindProperty]
attribute on the relevant PageModel properties, asp-for
attribute in your input tag helpers to establish two-way binding in the UI (Razor content page)return Page()
in the event that ModelState.IsValid == false
. Here are the minimal steps required to demonstrate this:
A form:
<form method="post">
<input asp-for="FirstName"/><span asp-validation-for="FirstName"></span><br />
<input type="submit" />
</form>
And a PageModel:
public class FormValidationModel : PageModel
{
[BindProperty, StringLength(5)]
public string FirstName { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("index");
}
}
Thanks Mike for Reply. Well i know this can work but what it does not work when you bind a property with dropdown(select). for example if i bind a dropdown and select its value to "ABC" on form and post back , and if model state fails, i can't rebind that select list and make ABC as selected value on form
Mike Brind, i sorted this our. Thanks for you help
How did you sort it?
@JacobAlley The select tag helper will automatically sort it for you if the property used to represent the selected value is made bindable by adding the
[BindProperty]
attribute to it.