c# - 在 Controller 中编辑后 ModelState 不验证嵌套模型

标签 c# asp.net-mvc entity-framework

我嵌套了如下两个 ViewModel:

public class FirstViewModel
{
    public SecondViewModel SecondViewModel { get; set; }
}

public class SecondViewModel
{
    [Range(1, 12)]
    public int month { get; set; }
}

如果我输入 month = 13;然后调用ModelState.IsValid (在 Controller 中)验证总是 true .

编辑:

这是 Controller :

public ActionResult Create()
{
    return PartialView(new FirstViewModel);    
}

public HttpStatusCodeResult Create (FirstViewModel viewModel){

    viewModel.SecondViewModel = new SecondViewModel();
    viewModel.SecondViewModel.month = 13;

    if (ModelState.IsValid)
    {
        return new HttpStatusCodeResult(200);
    }
    else
    {
        return new HttpStatusCodeResult(304);
    }
}

我正在对问题进行抽象,那些不是真正的变量。

最佳答案

您的问题说明您在 Controller 中“调用 ModelState.Validate”。没有这样的方法,所以我假设你的意思是 if (ModelState.IsValid)

模型绑定(bind)过程的第一步是初始化方法的参数,在您的例子中是 FirstViewModel 的新实例。然后根据表单数据、路由值、查询字符串值等设置模型的值,并将与模型属性相关的任何验证错误添加到 ModelState

随后修改模型中的属性值对 ModelState 没有影响,因此如果 month 的初始值有效,则 ModelState.IsValid 将返回 true,无论设置 viewModel.SecondViewModel.month = 13;

如果你想重新验证你的模型,你需要使用TryUpdateModel它返回一个 bool 指示更新是否成功

public HttpStatusCodeResult Create (FirstViewModel viewModel)
{
  viewModel.SecondViewModel = new SecondViewModel();
  viewModel.SecondViewModel.month = 13;
  if (TryUpdateModel(viewModel)
  {
    return new HttpStatusCodeResult(200);
  }
  else
  {
    return new HttpStatusCodeResult(304);
  }
}

关于c# - 在 Controller 中编辑后 ModelState 不验证嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647747/

相关文章:

c# - ComboBox 项目到多个文本框

c# - C# 中枚举的替代方法 - 嵌套

c# - 确定何时以及在文本框中添加或删除哪个字符

c# - 更改 ajax 请求的 response.statuscode 引发错误 "Server cannot set status after HTTP headers have been sent"

asp.net-mvc - 是否可以基于子域创建 ASP.NET MVC 路由?

c# - 运行大型 SQL 语句并填充 gridview

asp.net-mvc - 测试使用DbContext的存储库的最佳方法

entity-framework - AWS 上的 .NET Core Entity Framework

c# - 如何创建方面装饰器来处理 EF 事务

c# - 更新数据库上下文以包含 View 模型