ASP NET CORE 2 我有以下页面模型代码
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");
}
}
当我尝试发布错误的图像时,!ModelState.IsValid yeilds true和Page()被调用。我明白了
NullReferenceException: Object reference not set to an instance of an object.
中的Model.ItemModel.Categories
Categories
是通常由_itemService.GetCreateViewModel()从db下载的多个选择列表之一。
我不明白Page()
会发生什么。为什么不使用表单中的旧数据?如何重新呈现包含验证错误的页面(我在cshtml中有asp-validation-for
)?我尝试this.ItemModel = itemModel
,我没有得到Null引用,但没有看到任何验证错误,并且之前的选择列表值未保存。
答案 0 :(得分:3)
return Page
与在正常的MVC Controller操作中调用return View()
相同。
当提交的表单有验证错误(传递给服务器)时,
OnPostAsync
处理程序方法调用Page
帮助程序方法。Page
返回PageResult
的实例。返回Page
类似于控制器中的操作返回View
的方式。PageResult
是处理程序方法的默认返回类型。返回void
的处理程序方法呈现页面。
更新页面模型属性以允许视图绑定到模型。
public class CreateModel : PageModel {
private readonly IItemService _itemService;
public CreateModel(IItemService itemService) {
_itemService = itemService;
}
[BindProperty]
public ItemCreateViewModel ItemModel { get; set; }
// all related data downloaded from db, so all rendered correctly
public async Task<IActionResult> OnGetAsync() {
ItemModel = await _itemService.GetCreateViewModel();
return Page();
}
public async Task<IActionResult> OnPostAsync() {
if (!ModelState.IsValid) {
return Page();
}
var item = _itemService.CreateItem(ItemModel);
var image = await ImagesController.ProcessFormImage(ItemModel.ImageUpload.UploadPhoto, item.Id, ModelState);
if (!ModelState.IsValid) {
return Page();
}
await _itemService.SaveItemImage(image);
_itemService.CreateItem(ItemModel);
return RedirectToPage("./Index");
}
}