简体   繁体   English

Asp.net core 如何对视图组件进行模型验证

[英]Asp.net core how to do model validation on View Components

I currently have a view component which contains a form.我目前有一个包含表单的视图组件。 Once this form is submitted it is sent to the controller and the model state is checked.一旦这个表单被提交,它就会被发送到控制器并检查模型状态。 Normally after the model state is not valid I just reload the view with the model passed in and display the values in the with the validation error messages.通常在模型状态无效后,我只需使用传入的模型重新加载视图并显示带有验证错误消息的值。 My issue is because I'm using a view component how do I get this model with the validation error messages back to the view component from the controller.我的问题是因为我正在使用视图组件,如何将带有验证错误消息的模型从控制器返回到视图组件。 I need to get them model through the view and to the view component.我需要通过视图和视图组件获取它们的模型。

Say that I submit the form with data that would fail model validation and the controller method below is hit, after the model state is checked and fails, how would I return it back to the view component?假设我提交的表单带有模型验证失败的数据并且下面的控制器方法被命中,在检查模型状态并失败后,我将如何将其返回给视图组件?

public async Task<IActionResult> UpdateDetails(CustomerDetailsViewModel customerDetailsViewModel)
{
    if (ModelState.IsValid)
    {
         ...
    }
    //How to return 'customerDetailsViewModel' back to view component
}

All you need is to return the view of the model following the snippet below:您只需要按照以下代码段返回模型的视图:

if(ModelState.IsValid)
{
  //What you want to do

}
else
{
return View(customerDetailsViewModel);
}

Returning the view of customerDetailsViewModel will return all the data previously filled by the customer返回customerDetailsViewModel的视图会返回之前客户填写的所有数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM