.net - ASP.NET MVC 验证组?

标签 .net asp.net-mvc asp.net-mvc-3 validation

我有一个表单,我想根据按下的提交按钮要求不同的字段。示例:如果您按下提交按钮 1,则字段 A 是必需的,但如果您按下提交按钮 2,则只需要字段 B。如果我仍在使用 Web 表单,我会为每个按钮/验证器组合分配不同的“验证组”。 有没有办法在 MVC 中做到这一点,最好在模型上使用数据注释? 我更愿意用一个解决方案来实现客户端和服务器验证,但我会尽我所能......

提前致谢!

最佳答案

启用客户端验证的自定义验证属性如何(这样您就可以同时获得客户端和服务器验证)?下面的解决方案使用 jQuery 不显眼的验证。要使用它,您需要为所有按钮指定特定名称并将名称传递给验证属性。该按钮还需要具有某种类型的值,以便可以回发(以便服务器端代码可以对其进行测试,即 <input type="submit" name="myButton" value="1" /> )。我还没有测试过这段代码,所以我不确定它是否开箱即用。您可能需要制作一些模组:

您的模型的验证属性:

public class RequiredIfButtonClickedAttribute : ValidationAttribute, IClientValidatable
{
    private RequiredAttribute _innerAttribute = new RequiredAttribute();
    public string ButtonName { get; set; }

    public RequiredIfButtonClickedAttribute(string buttonName)
    {
        ButtonName = buttonName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if ((value == null && !string.IsNullOrEmpty(HttpContext.Current.Request.Form[ButtonName])))
        {
            if (!_innerAttribute.IsValid(value))
            {
                return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }

    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "requiredifbuttonclicked" };
        rule.ValidationParameters.Add("buttonname", ButtonName);
        yield return rule;
    }

    #endregion
}

客户端脚本:
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

// When a button is clicked remove the clicked button class from all buttons and add it to the on that was clicked
$(":submit").click(function () {
    $(":submit").removeClass('clickedButton');
    $(this).addClass('clickedButton');
});

$.validator.addMethod('requiredifbuttonclicked',
    function (value, element, parameters) {

        // if the condition is true, reuse the existing 
        // required field validator functionality
        if ($(".clickedButton").val("name") === parameters['buttonname'])
            return $.validator.methods.required.call(
              this, value, element, parameters);

        return true;
    }
);

$.validator.unobtrusive.adapters.add(
    'requiredifbuttonclicked',
    ['buttonname'],
    function (options) {
        options.rules['requiredifbuttonclicked'] = {
            buttonname: options.params['buttonname']
        };
        options.messages['requiredifbuttonclicked'] = options.message;
});

并像这样使用它:
[RequiredIfButtonClicked("myButtonName")]
public string Name { get; set; }

关于.net - ASP.NET MVC 验证组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7340751/

相关文章:

.net - WPF 命令和事件有什么区别?

c# - 如何获取回收站目录?

c# - 将 DataTable 保存到数据库表中

.net - 如何允许所有用户通过集成身份验证访问网站中的一条路由?

c# - MVC 核心集 IHostingEnvironment 开发

validation - 本地化 MVC3 验证消息

c# - 如何使用 .NET XML 序列化序列化正则表达式类型

jquery - 在 asp.net mvc 5 中发布之前使用 jquery 检查所有验证

c# - 使用 c# asp.net mvc3 在单个页面上绘制多个图表

jquery - 从 MVC3 中的 Controller 向 AJAX 调用返回错误