手动调用 ModelState 验证

发布于 2024-11-16 02:19:51 字数 853 浏览 4 评论 0原文

我正在使用 ASP.NET MVC 3 代码优先,并且已将验证数据注释添加到我的模型中。这是一个示例模型:

public class Product
{
    public int ProductId { get; set; }

    [Required(ErrorMessage = "Please enter a name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter a description")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [Required(ErrorMessage = "Please provide a logo")]
    public string Logo { get; set; }
}

在我的网站中,我有一个多步骤过程来创建新产品 - 步骤 1 输入产品详细信息,步骤 2 其他信息等。在每个步骤之间,我将每个对象(即 Product 对象)存储在会话,因此用户可以返回到该过程的该阶段并修改他们输入的数据。

在每个屏幕上,我都有客户端验证与新的 jQuery 验证配合良好。

最后阶段是确认屏幕,之后在数据库中创建产品。但是,由于用户可以在阶段之间跳转,因此我需要验证对象(产品和其他一些对象)以检查它们是否已正确完成数据。

有没有什么方法可以以编程方式对具有数据注释的对象调用 ModelState 验证?我不想遍历对象的每个属性并进行手动验证。

如果可以更轻松地使用 ASP.NET MVC 3 的模型验证功能,我愿意接受有关如何改进此过程的建议。

I'm using ASP.NET MVC 3 code-first and I have added validation data annotations to my models. Here's an example model:

public class Product
{
    public int ProductId { get; set; }

    [Required(ErrorMessage = "Please enter a name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter a description")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [Required(ErrorMessage = "Please provide a logo")]
    public string Logo { get; set; }
}

In my website I have a multi-step process to create a new product - step 1 you enter product details, step 2 other information etc. Between each step I'm storing each object (i.e. a Product object) in the Session, so the user can go back to that stage of the process and amend the data they entered.

On each screen I have client-side validation working with the new jQuery validation fine.

The final stage is a confirm screen after which the product gets created in the database. However because the user can jump between stages, I need to validate the objects (Product and some others) to check that they have completed the data correctly.

Is there any way to programatically call the ModelState validation on an object that has data annotations? I don't want to have to go through each property on the object and do manual validation.

I'm open to suggestions of how to improve this process if it makes it easier to use the model validation features of ASP.NET MVC 3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

空袭的梦i 2024-11-23 02:19:51

您可以在 Controller 操作中调用 ValidateModel 方法(此处的文档)。

You can call the ValidateModel method within a Controller action (documentation here).

╄→承喏 2024-11-23 02:19:51

ValidateModel 和 TryValidateModel

您可以在控制器范围内使用ValidateModelTryValidateModel

验证模型时,所有属性的所有验证器都会
如果至少一个表单输入绑定到模型属性,则运行。这
ValidateModel 与 TryValidateModel 方法类似,不同之处在于
TryValidateModel 方法不会抛出 InvalidOperationException
如果模型验证失败则抛出异常。

ValidateModel - 如果模型无效,则抛出异常。

TryValidateModel - 返回布尔值,指示模型是否有效。

class ValueController : Controller
{
    public IActionResult Post(MyModel model)
    {
        if (!TryValidateModel(model))
        {
            // Do something
        }

        return Ok();
    }
}

逐一验证模型

如果您逐一验证模型列表,您可能需要通过调用 ModelState.Clear() 来重置每次迭代的 ModelState。

链接到文档

ValidateModel and TryValidateModel

You can use ValidateModel or TryValidateModel in controller scope.

When a model is being validated, all validators for all properties are
run if at least one form input is bound to a model property. The
ValidateModel is like the method TryValidateModel except that the
TryValidateModel method does not throw an InvalidOperationException
exception if the model validation fails.

ValidateModel - throws exception if model is not valid.

TryValidateModel - returns bool value indicating if model is valid.

class ValueController : Controller
{
    public IActionResult Post(MyModel model)
    {
        if (!TryValidateModel(model))
        {
            // Do something
        }

        return Ok();
    }
}

Validate Models one-by-one

If you validate a list of models one by one, you would want to reset ModelState for each iteration by calling ModelState.Clear().

Link to the documentation

狼性发作 2024-11-23 02:19:51
            //
            var context = new ValidationContext(model);

            //If you want to remove some items before validating
            //if (context.Items != null && context.Items.Any())
            //{
            //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Longitude").FirstOrDefault());
            //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Latitude").FirstOrDefault());
            //}

            List<ValidationResult> validationResults = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(model, context, validationResults, true);
            if (!isValid)
            {
                //List of errors 
                //validationResults.Select(r => r.ErrorMessage)
                //return or do something
            }
            //
            var context = new ValidationContext(model);

            //If you want to remove some items before validating
            //if (context.Items != null && context.Items.Any())
            //{
            //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Longitude").FirstOrDefault());
            //    context.Items.Remove(context.Items.Where(x => x.Key.ToString() == "Latitude").FirstOrDefault());
            //}

            List<ValidationResult> validationResults = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(model, context, validationResults, true);
            if (!isValid)
            {
                //List of errors 
                //validationResults.Select(r => r.ErrorMessage)
                //return or do something
            }
贩梦商人 2024-11-23 02:19:51

我发现它可以工作并且完全按照预期执行..在 GET 操作方法上显示新检索的对象的 ValidationSummary...在任何 POST 之前

Me.TryValidateModel(MyCompany.OrderModel)

I found this to work and do precisely as expected.. showing the ValidationSummary for a freshly retrieved object on a GET action method... prior to any POST

Me.TryValidateModel(MyCompany.OrderModel)
笔落惊风雨 2024-11-23 02:19:51

Dot net core中,您可以使用TryValidateModel。在调用它之前,您需要重置 modelState。

    //you may need to put any logical change on model
    model.IsDefault = model.IsDefault??false;//I was having IsDefault as empty string
    //clear the model state
    ModelState.Clear();
    
    if(TryValidateModel(model)){
        //your code
    }else{
        //handle the invalid model
    }

或者您可以删除不想使用

ModelState.Remove("FieldName");

FieldName 进行验证的字段,可以是模型中键的名称,或者如果该字段是类对象的属性,则字段名称将类似于 在DotNet MVC

ModelState.Remove("ClassName.FieldName");

,您可以使用

ModelState.Clear();
Validate(entity);
//or remove the field 
ModelState.Remove("FieldName");
if (ModelState.IsValid) {
        //your code
}else{
        //handle the invalid model
}

In Dot net core you can use TryValidateModel. Before calling it, you need to reset your modelState.

    //you may need to put any logical change on model
    model.IsDefault = model.IsDefault??false;//I was having IsDefault as empty string
    //clear the model state
    ModelState.Clear();
    
    if(TryValidateModel(model)){
        //your code
    }else{
        //handle the invalid model
    }

Or you can remove the field which you don't want to put in validation with

ModelState.Remove("FieldName");

The FieldName can the name of the key in the model or if the field is a class object's property then field name will be like bellow

ModelState.Remove("ClassName.FieldName");

In DotNet MVC, you can use

ModelState.Clear();
Validate(entity);
//or remove the field 
ModelState.Remove("FieldName");
if (ModelState.IsValid) {
        //your code
}else{
        //handle the invalid model
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文