Using ASP.NET Core Razor Pages, I have a form that returns a Person by Id, and allows the user to update the record or add a new Person OnPost.
When posting a new record, I expect it to return to the same page and display the updated Id, but it remains as 0.
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public string FavouriteDoughnut { get; set; }
}
The form:
@page "{personId:int}"
@model Pages.EditModel
<form method="post">
<label asp-for="Person.PersonId">Id</label>
<input asp-for="Person.PersonId" readonly>
<label asp-for="Person.Name">Name</label>
<input asp-for="Person.Name">
<label asp-for="Person.FavouriteDoughnut">Doughnut?</label>
<input asp-for="Person.FavouriteDoughnut">
<button type="submit>Save</button>
</form>
[BindProperty(SupportsGet=true)]
public Person Person { get; set; }
public async void OnGet(int personId)
{
if(personId > 0)
{
Person = await _dbContext.People.FindAsync(personId);
return;
}
Person = new Person();
}
public void OnPost()
{
Person = UpdatePerson(Person);
}
private void UpdatePerson(Person person)
{
_dbContext.People.Update(person);
await _dbContext.SaveChanges();
return person;
}
Do I need to redirect to the Edit page? When I inspect the Person OnPost I can see that it is updated and the page refreshes, it just doesn't get populated with the new Id.
Check your model design, PersonId
is the PrimaryKey
in database, when user post a new record, The value of PersonId
is self-incrementing rather than depending on the value of the PersonId
in the new record. When user want to post a new record, The input box of PersonId
will be automatically locked, Not allowing user to enter anything, So the page will not receive the value of PersonId
, after the page refresh, It will not display the real value of PersonId
.
In my opinion, Showing the primary key to the user is not necessary, But if you want to do that, You can query by PersonId
and return the result to the page after adding the new record or just RedirectToPage("/Edit", new{ personId = Person.Id }
, I recommend you to use the second method.