手动调用 ModelState 验证 [英] Manually invoking ModelState validation

查看:30
本文介绍了手动调用 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; }
}

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

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.

在每个屏幕上,我都使用新的 jQuery 验证进行客户端验证.

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.

有没有办法以编程方式对具有数据注释的对象调用 ModelState 验证?我不想检查对象上的每个属性并进行手动验证.

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.

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

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.

推荐答案

您可以在 Controller 操作(文档在这里).

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

这篇关于手动调用 ModelState 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆