MVC验证独特 [英] MVC validation for unique

查看:115
本文介绍了MVC验证独特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个MVC应用程序,我用来插入更新发票:

Hi I have an MVC app that I used to insert update invoices:

public class Invoice : IEntity, IValidatableObject
    {
        public virtual int InvoiceId { get; set; }

        [Required(ErrorMessage = "Invoice Number is a required field.")]
        [Column(TypeName = "varchar")]
        [StringLength(20)]
        [Display(Name = "Invoice Number:")]
        public virtual string InvoiceNumber { get; set; }

        [Required(ErrorMessage = "Organisation is a required field.")]
        [Display(Name = "Organisation:")]
        public int OrganisationId { get; set; }

              ...
}

问题是我有一个要求组织和发票号码的组合必须是唯一的。

The problem is I have a requirement "The combination of organisation and invoice number must be unique.

因此​​,这已经通过在数据库中的DBA成立。所以,如果我试图这样做将返回一个异常。

So this has been set up by the DBA in the database. So if I try to do this it will return an exception.

有没有一种方法,而不是显示例外,抓住它,并添加自定义错误消息的验证摘要?

Is there a way instead of displaying the exception to catch it and add a custom error message to the validation summary?

推荐答案

您可以捕获该异常和错误添加到模型状态,这样你的客户code处理所有的错误一样。是这样的:

You could catch the exception and add the error to the model state so that your client code handles all errors the same way. Something like:

ModelState.AddModelError("InvoiceNumber", "The combination of organisation and invoice number must be unique.");

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

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