【问题标题】:How to exclude certain properties when validating model with TryValidateModel使用 TryValidateModel 验证模型时如何排除某些属性
【发布时间】:2023-03-07 07:54:01
【问题描述】:

我正在处理一个 ASP.NET MVC 3 项目,需要从服务器端验证中排除某些属性。我正在寻找类似这个问题Is it possible to override the required attribute on a property in a model? 的内容,但我不想再次绑定模型,因为我已经对其进行了更改(据我了解,这就是 TryUpdateModel 会做的)。

来自相关问题

public ActionResult SomeAction()
{
 var model = new BaseModel();

 if (TryUpdateModel(model, null, null, new[] { "RequiredProperty" })) // fourth parameter is an array of properties (by name) that are excluded
 {
      // updated and validated correctly!
      return View(model);
 }
 // failed validation
 return View(model);
}

我想验证已更新的模型,不包括某些属性。我应该只使用链接问题中建议的 hackedbychinese 之类的 TryUpdateModel 吗?它可以改变属性的值吗?

【问题讨论】:

    标签: asp.net-mvc-3 validation


    【解决方案1】:

    我最终使用了 jquery 验证规则删除方法。

    $("#fax_DisplayPhoneNumber").rules("remove", "required");
    

    这会覆盖模型中传真 DisplayPhoneNumber 属性上的 [Required] 标记,因此它不再是必需的输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-18
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多