我们可以使用模型绑定器和模型验证器来确保ViewModel属性不为空。下面是一个示例代码:
ViewModel类:
public class MyViewModel
{
[Required]
public string Property1 { get; set; }
[Required]
public int Property2 { get; set; }
}
Controller类:
public class MyController : Controller
{
public IActionResult MyAction(MyViewModel viewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// The ViewModel's properties are not null, you can use them here
return View();
}
}
在此示例中,我们在ViewModel的属性上添加了[Required]属性。当属性为空时,模型绑定器会失败,并将ModelState标记为无效。我们可以在Action方法中使用ModelState.IsValid属性来检查ViewModel的属性是否为空。如果ModelState是无效的,则可以使用BadRequest方法返回400状态代码和ModelState对象,否则将ViewModel传递给Action方法进行下一步操作。