c# - 刷新 ModelState 以消除错误

标签 c# asp.net-mvc modelstate

刷新模型状态

您好,我有一个关于 ASP.NET MVC Controller 中的 ModelState 的问题。

当用户从 View 中选择某个选项时,“认证”的开始日期和结束日期将根据输入的其他日期设置。

问题是认证日期返回为 null,而我们的 CertificationMetaData 类将字段指定为 [Required],因此一旦加载操作,ModelState 就会无效。

手动删除 ModelSate 错误可以让这个工作,但我想知道是否有更好的方法来做到这一点?有没有办法刷新 ModelState?我应该让字段不需要吗?还是应该使用 javascript 从 View 中添加日期值?

public ActionResult Create(FormCollection fc, Certification certification, Absence absence)
{
    if (certification.CertificationTypeID == 1)
    {
        certification.CertificationStartDate = absence.StartDate;
        certification.CertificationEndDate = absence.StartDate.AddDays(7);
        this.ModelState.Remove("CertificationStartDate");
        this.ModelState.Remove("CertificationEndDate");
    }

    if (this.ModelState.IsValid)
    {
        // save
        return RedirectToAction("Index");
    }
     return View();
}

您还可以看到,我已经对证书类型的 ID 值进行了硬编码。将值与查找表值进行比较的最佳方法是什么?枚举是最好的方法吗?

谢谢

最佳答案

以下方法刷新模型状态并允许您使模型设计与[必需]属性等保持一致。

在我的例子中,我希望我的模型有一个必填字段,普通级别的用户使用 API 无法更改,所以我这样做了:

ModelState.Remove("ChangeDate");
ModelState.Add("ChangeDate", new ModelState());
ModelState.SetModelValue("ChangeDate", new ValueProviderResult(club.ChangeDate, DateTime.Now.ToString(), null));

这样您就不需要删除必填字段,也不需要在 javascript 中提供日期。

关于c# - 刷新 ModelState 以消除错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1613615/

相关文章:

ASP.NET MVC 4 "Create"页面提交导致无效的 ModelState

c# - 在没有 DBSet 的情况下使用 c# linq 执行 SQL Server 存储过程

c# - MongoDB C# 驱动程序中的 BsonValue 和自定义类

c# - 为什么 Nullable<T> 被视为结构而不是类?

c# - 使用 Entity Framework 连接到数据库时出现错误

c# - ASP.NET MVC : How do I change where Ajax. BeginForm 将在页面加载后发布到?

asp.net-mvc - MVC 4中的脚手架 Controller ,错误: "Error: Unable to retrieve metadata for ' Model'.的解决方案参数 'connectionstring'不能为空

c# - 如何将工具提示添加到数据网格单元格

c# - ASP.NET MVC Controller 发布方法单元测试 : ModelState. IsValid 始终为真

asp.net-mvc - 带有 JsonResult : ModelState is always valid 的 ASP.NET MVC 3