ASP NET CORE 2 I have following page model code
public class CreateModel : PageModel
{
private readonly IItemService _itemService;
public ItemCreateViewModel ItemModel { get; set; }
public CreateModel(IItemService itemService)
{
_itemService = itemService;
}
// all related data downloaded from db, so all rendered correctly
public async Task OnGet(ItemCreateViewModel itemModel)
{
ItemModel = await _itemService.GetCreateViewModel();
}
public async Task<IActionResult> OnPost(ItemCreateViewModel itemModel)
{
if (!ModelState.IsValid)
{
return Page();
}
var item = _itemService.CreateItem(itemModel);
var image = await ImagesController.ProcessFormImage(itemModel.ImageUpload.UploadPhoto, item.Id, ModelState);
if (!ModelState.IsValid)
{
//trouble is somewhere here
return Page();
}
await _itemService.SaveItemImage(image);
_itemService.CreateItem(itemModel);
return RedirectToPage("./Index");
}
}
When I try to post wrong image, !ModelState.IsValid yeilds true and Page() invoked. I get
NullReferenceException: Object reference not set to an instance of an object.
in Model.ItemModel.Categories
where Categories
is one of serveral select lists normally downloaded from db by _itemService.GetCreateViewModel().
I do not understand what happens at Page()
. Why isn't old data from form used? How can I rerender page with validation errors (I have asp-validation-for
in cshtml)? I tried this.ItemModel = itemModel
, and I get no more Null reference, but do not see any validation errors, and previous select lists values not saved.
View()
in normal MVC – Nkosi