asp.net-mvc 是否可以手动更新 ModelState.IsValid?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10296361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:53:28  来源:igfitidea点击:

Is it possible to update ModelState.IsValid manually?

asp.net-mvcasp.net-mvc-3

提问by Old Geezer

I would like to use the built-in validation features as far as possible. I would also like to use the same model for CRUD methods.

我想尽可能使用内置的验证功能。我还想对 CRUD 方法使用相同的模型。

However, as a drop down list cannot be done using the standard pattern, I have to validate it manually. In the post back method, I would like to just validate the drop down list and add this result to ModelState so that I don't have to validate all the other parameters which are done with Data Annotation. Is it possible to achieve this?

但是,由于无法使用标准模式完成下拉列表,因此我必须手动对其进行验证。在回发方法中,我只想验证下拉列表并将此结果添加到 ModelState,这样我就不必验证使用数据注释完成的所有其他参数。有可能实现这一目标吗?

I may be mistaken about the drop down list, but from what I read, the Html object name for a drop down list cannot be the same as the property in the Model in order for the selected value to be set correctly. Is it still possible to use Data Annotation with this workaround?

我可能对下拉列表有误解,但从我读到的内容来看,下拉列表的 Html 对象名称不能与模型中的属性相同,以便正确设置所选值。是否仍然可以在此解决方法中使用数据注释?

Thanks.

谢谢。

回答by Gabriele Petrioli

You can use the addModelError

您可以使用 addModelError

ModelState.AddModelError(key,message)

when you use that, it will invalidate the ModelState so isValidwill return false.

当您使用它时,它将使 ModelState 无效,因此isValid将返回 false。



Update
after seeing the comment to @Pieter's answer

看到对@Pieter 的回答的评论后更新

If you want to exclude an element from affecting the isValid()result, you can use the ModelState.Remove(field)method before calling isValid().

如果要排除某个元素影响isValid()结果,可以ModelState.Remove(field)在调用之前使用该方法isValid()

回答by Tim Coker

Another option is to inherit IValidatableObjectin your model. Implement its Validatemethod and you can leave all other validation in place and write whatever code you want in this method. Note: you return an empty IEnumerable<ValidationResult>to indicate there were no errors.

另一种选择是IValidatableObject在您的模型中继承。实现它的Validate方法,您可以保留所有其他验证并在此方法中编写您想要的任何代码。注意:您返回一个空IEnumerable<ValidationResult>值表示没有错误。

public class Class1 : IValidatableObject
{
    public int val1 { get; set; }
    public int val2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var errors = new List<ValidationResult>();
        if (val1 < 0)
        {
            errors.Add(new ValidationResult("val1 can't be negative", new List<string> { "val2" }));
        }
        if (val2 < 0)
        {
            errors.Add(new ValidationResult("val2 can't be negative", new List<string> { "val2" }));
        }
        return errors;
    }
}

EDIT: After re-reading the question I don't think this applicable to this case, but I'm leaving the answer here in case it helps someone else.

编辑:重新阅读问题后,我认为这不适用于这种情况,但我将答案留在这里,以防它对其他人有所帮助。

回答by Pieter Germishuys

You cannot manually set the ModelState.IsValid property but you can add messages to the ModelState that will ensure that the IsValid is false.

您无法手动设置 ModelState.IsValid 属性,但可以向 ModelState 添加消息以确保 IsValid 为 false。

ModelState.AddModelError();

回答by Chtiwi Malek

yes, you can achieve this (also you will use the same model for CRUD methods) :

是的,您可以实现这一点(您还将对 CRUD 方法使用相同的模型):

Example MODEL

示例模型

public class User 
{
    public virtual int Id{ get; set; }
    public virtual Role Role { get; set; }
}
public class Role 
{        
    [Required(ErrorMessage = "Id Required.")]
    public virtual int Id { get; set; }
    [Required(ErrorMessage = "Name Required.")]
    public virtual string Name { get; set; }
}

Example VIEW with validation on the dropdownlist

带有下拉列表验证的示例 VIEW

@Html.DropDownListFor(m => m.Role.Id, (SelectList)ViewBag.gRoles, "-- Select --")
@Html.ValidationMessageFor(m => m.Role.Id)

CONTROLLER: clearing the required (but not needed here) fields

控制器:清除必填(但此处不需要)字段

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Creedit(User x)
{
    x.Role = db.RoseSet.Find(x.Role.Id);
    if (x.Role != null)
    {
        ModelState["Role.Name"].Errors.Clear();

    }

    if (ModelState.IsValid)
    {
      // proceed
    }
    else
    {
      // return validation error
    }
}