Reputation: 61
When I select item then OnGetDetails(int id, int toggle) method is activated and loads object from DB to property.
[BindProperty]
public Creature Creature { get; set; }
public void OnGetDetails(int id, int toggle){
Creature = new GetCreature(_ctx).Get(id);
}
public Creature Get(int id){
return _ctx.Creatures.Include(i => i.Items).FirstOrDefault(x => x.Id == id);
} // Get()
I have verified in debugger that it assigns the object correctly.
But when I want to use that object's property in OnPost method then debugger shows it as null. As if in the meantime reassigned a value to the property as an empty object. I checked that the default OnGet method is not activated. I just do not understand why value is lost and how to prevent it from happening.
public async Task<IActionResult> OnPostDeleteItemAsync(int id){
CreatureItem item = Creature.Items.FirstOrDefault(x => x.ItemId == id);
if (item == null) return RedirectToPage("Creature");
await new EditCreature(_ctx).DeleteItem(Creature, id);
return Redirect(UrlString);
}
Tried workaround with form but I was only able to pass object's id not the whole object.
<input type="hidden" asp-for="Creature.Id" /> works
<input type="hidden" asp-for="Creature" /> don't work
Git:
https://github.com/Mlorism/LastTemple/blob/master/LastTemple/Pages/Manage/Creature.cshtml
https://github.com/Mlorism/LastTemple/blob/master/LastTemple/Pages/Manage/Creature.cshtml.cs
Upvotes: 0
Views: 1120
Reputation: 9632
Properties of PageModel
are not stored between requests. Even if you have a property assigned on GET
request it won't be there on POST
request because these are two different requests. During POST
Creature
property is null because it's being bound from request but no data was sent. And your "workaround" addresses this issue, it sends data on request to fill Creature
property with values. Moreover this is not a workaround, this is how things are supposed to work.
If you want a property to be instantiated you need to pass some values via form, or query parameters if it's a GET
request.
Upvotes: 4