如何获取模型属性的id以与MVC3中的自定义IClientValidatable一起使用

Mr *_*ell 3 c# validation asp.net-mvc-3

我正在尝试编写一个自定义验证属性,该属性将有条件地要求基于模型的布尔属性的字段.

我有我的属性实现IClientValidatable.我有要检查的属性的名称,但我不知道如何获取目标属性的客户端ID.

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

    rule.ValidationParameters["target"] = clientTarget;

    yield return rule;
}
Run Code Online (Sandbox Code Playgroud)

javascript:

$.validator.addMethod("requiredif", function (value, element, target)
{
    //check on value of target
});

$.validator.unobtrusive.adapters.addSingleVal("requiredif", "target");
Run Code Online (Sandbox Code Playgroud)

如何获取目标属性的客户端ID,以便客户端javascript可以检查值?

Bob*_*lth 6

我拿了Nathan的优秀答案,添加了一些注释,并将其包装在一个名为GetHtmlId的扩展方法中,所以现在我可以使用这样的代码来获取同一页面上任何其他元素的HTML ID:

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

        // Find the value on the control we depend on...
        string depProp = this.GetHtmlId(metadata, context, this.DependentPropertyName);

        rule.ValidationParameters.Add("dependentproperty", depProp);

        yield return rule;
    }
Run Code Online (Sandbox Code Playgroud)

这是扩展方法:

using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace sbs.Lib.Web.ValidationAttributes
{
    public static class IClientValidatableExtensions
    {
        /// <summary> Returns the HTML ID of the specified view model property. </summary>
        /// <remarks> Based on: http://stackoverflow.com/a/21018963/1637105 </remarks>
        /// <param name="metadata"> The model metadata. </param>
        /// <param name="viewContext"> The view context. </param>
        /// <param name="propertyName"> The name of the view model property whose HTML ID is to be returned. </param>
        public static string GetHtmlId(this IClientValidatable me,
                                       ModelMetadata metadata, ControllerContext context,
                                       string propertyName)
        {
            var viewContext = context as ViewContext;

            if (viewContext == null || viewContext.ViewData.TemplateInfo.HtmlFieldPrefix == string.Empty) {
                return propertyName;
            } else {
                // This is tricky.  The "Field ID" returned by GetFullHtmlFieldId is the HTML ID
                // attribute created by the MVC view engine for the property whose validator is
                // being set up by the caller of this routine. This code removes the property
                // name from the Field ID, then inserts the specified property name.
                // Of course, this only works for elements on the same page as the caller of
                // this routine!
                string fieldId = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("");
                fieldId = fieldId.Remove(fieldId.LastIndexOf("_"));
                return fieldId + "_" + propertyName;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)