ASP.NET MVC自定义验证的名单,LT;字符串> [英] ASP.NET MVC Custom validation for a List<string>

查看:115
本文介绍了ASP.NET MVC自定义验证的名单,LT;字符串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 5以及在客户端希望使用JQuery不引人注目的验证。

I am using ASP.NET MVC 5 and on the client side want to use JQuery unobtrusive validation.

以下是我的模型:

 public class CompanyModel
    {
        public CompanyModel()
        {
            Employees = new List<EmployeeModel>();              
        }
        public int CompanyId{ get; set; }

        public List<EmployeeModel> Employees { get; set; }        
    }

    public class EmployeeModel
    {
        public EmployeeModel()
        {
            Values = new List<string>();
        }

        public string Id { get; set; }

        public string Name { get; set; }

        [RequiredIf("IsRequired", true, "Atleast one value is required")]
        public List<string> Values { get; set; }

        public bool IsRequired { get; set; }
    }

我是能够实现RequiredIf定制属性成功在服务器端。但我努力让客户端验证会...

I was able to implement the RequiredIf custom attribute successfully on the server side. But I'm struggling to get the client side validation going...

在通过员工列表视图我环路和值集合势必

In the view I loop through the employees list and the values collection is bound

@for (var index = 0; index < Model.Employees.Count; index++)
{
      /// some other code

    @for (int i = 0; i < Model.employees[index].Values.Count; i++)
    {
        @Html.TextBoxFor(m => m.Employees[index].Values[i], new {@autocomplete = "false" })
    }    
 }

该IsRequired属性是一个隐藏字段:

The IsRequired property is a hidden field:

@Html.HiddenFor(m => m.Employees[index].IsRequired)

以下是code我迄今为止的GetClientValidationRules方法。

The following is the code I have so far for the GetClientValidationRules method.

  public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientValidationRule
                {
                    ErrorMessage = ErrorMessage,
                    ValidationType = "requiredif"
                };               

                rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
                rule.ValidationParameters["dependentpropertyvalue"] = DependentPropertyValue.ToString().ToLower();

                yield return rule;            
            }

我看不到验证HTML(数据val- *)的属性添加到该值在HTML标记。而且我也不指望他们太多,因为我觉得我失去了一些东西。我如何获得价值集合填入HTML中的数据-VAL-requiredif属性的所有元素。

I don't see the validation html (data-val-*) attributes added to the values in the HTML markup. And I don't expect them too as I think I am missing something. How do I get all the elements of the values collection populated with the data-val-requiredif attributes in html.

任何想法?

FYI:在dependentpropertyId在HTML中填充像这样CompanyModel.Employees_0_IsRequired为雇员[0]

FYI: the dependentpropertyId in html is populated like so CompanyModel.Employees_0_IsRequired for Employee[0].

推荐答案

有少点包括 GetClientValidationRules()在验证属性的方法,因为它的目的是为了添加数据-VAL - * 属性该属性生成的表单控件,广告不产生财产(如果你没有,会绑定失败)。解决方法之一是处理表格 .submit()事件,检查集合中的至少一个项目有一个值,如果不取消提交和显示错误。

There is little point including the GetClientValidationRules() method in your validation attribute, because its purpose is to add the data-val-* attributes to the form control generated for that property, ad you don't generate an input for property Values (and if you did, binding would fail). One way to solve this is to handle the forms .submit() event, check if at least one item in the collection has a value, and if not cancel the submit and display the error.

修改您的视图,包括验证消息占位符,并添加一个类名的输入,选择

Modify your view to include the validation message place holder and add a class name to the inputs for selection

@for (var index = 0; index < Model.Employees.Count; index++)
{
    ....
    <div class="value-group"> // necessary for relative selectors
        @for (int i = 0; i < Model.employees[index].Values.Count; i++)
        {
            @Html.TextBoxFor(m => m.Employees[index].Values[i], new { @class="value", autocomplete = "false" })
        }
        @Html.ValidationMessageFor(m => m.Employees[index].Values)
   </div>
}

和包括下面的脚本

$('form').submit(function() { // use an id selector if you have added one to the form
    var isValid = true;
    var groups = $('.value-group');
    $.each(groups, function(index, item) {
        var group = $(this);
        var inputs = group.find('.value');
        if (inputs.filter(function () { return $(this).val().length > 0; }).length == 0) {
            isValid = false;
            group.find('span:last').append($('<span></span>').text('At least one value is required')).addClass('field-validation-error').removeClass('field-validation-valid');
        }
    });
    return isValid;
});

您可能还需要增加另一个脚本来处理每个输入的变化事件删除相关的错误信息如有的组中的投入,现在有一个值

You may also want to add another script to handle the change event of each input to remove the associated error message if any of the inputs in the group now have a value

这篇关于ASP.NET MVC自定义验证的名单,LT;字符串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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