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

问题描述

正常工作

 [MetadataType(typeof(Area_Validation))]
 public partial class Area
 {
    ...
 }

 public class Area_Validation
 {
 [Required(ErrorMessage = "Please add this field.")]
 public int Email { get; set; }

 [Required(ErrorMessage = "Please add this field")]
 public string Name { get; set; }
 }

但如何如果 Area_Validation 动态创建?例如订阅字段的是后端可以由用户创建,并最终像这样:

but how about if Area_Validation is dynamically created? for example Subscription Fields that on back-end can be created by the user and end up like this:

如何设置上的每个字段的自动验证

How can I set the Metadata on each field for auto validation?

目前我做的:

public class SubscriberFormViewModel
{
    public List<SubscriberFieldModel> Fields { get; private set; }
    public Calendar Calendar { get; private set; }
    public Company Company { get; private set; }

    public SubscriberFormViewModel()
    {
        // TODO: This is only for testing while validation is not set
    }
    public SubscriberFormViewModel(Decimal calendarId)
    {
        if (calendarId > 0)
        {
            SubscribersRepository db = new SubscribersRepository();

            Calendar calendar = db.GetCalendarById(calendarId);
            Company company = db.GetCompanyById(calendar.company_id);

            this.Fields = db.FindAllSubscriberFieldsByCalendar(calendarId);
            this.Calendar = calendar;
            this.Company = company;
        }
        else
            this.Fields = new List<SubscriberFieldModel>();
    }
}

和我想设置在中的所有字段属性

and I want to set the Metadata in all Fields property

在换句话说,这个字段从数据库填充,可以有几种类型,可以是一个字符串数量下拉菜单,等...有点像MailChimp字段属性:

In other words, this Fields are filled up from the Database and can have several types, can be a string, number, dropdown, etc ... kinda like MailChimp Fields Properties:

是有办法做到这一点programmaticaly 或我需要建立一个jQuery插件来验证它,并停止使用使用验证的MVC2?

is there a way to do this programmaticaly or I need to create a jQuery plugin to validate it and stop using use validation from MVC2 ?

感谢您

推荐答案

我不认为你可以做到这一点使用数据注释属性。

I dont think you can do this using Data Annotations attributes.

有在codePLEX一个项目,叫允许您添加使用的.Net code能说一口流利的方式验证规则。我从来没有使用过该项目,但似乎,也许可以帮助你在你的情况与动态创建的对象。

There is a project in Codeplex, called Fluent Validation that permit you to add validation rules in a fluent way using .Net code. I never used that project but it seems that maybe can help you in your case with dynamically created objects.

希望它帮助!

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

08-12 10:17