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

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

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

我的属性实现了 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;
}

JavaScript:

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

$.validator.unobtrusive.adapters.addSingleVal("requiredif", "target");

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

最佳答案

我采用了 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;
    }

这是扩展方法:

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;
            }
        }
    }
}

关于c# - 如何获取模型属性的 id 以便与 MVC3 中的自定义 IClientValidatable 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6950964/

相关文章:

c# - 当我每次刷新页面加载 button_click 事件时也运行

c# - Entity Framework 6 添加外键

jquery - 如何在 MVC 应用程序中返回 JSON 并循环遍历 jQuery 中返回的 json?

asp.net-mvc-3 - 使用 Intranet 应用程序实现用户角色的最佳方法

c# - 通过 GET 发送到 MVC Controller 的 GUID JSON 列表在到达时为空,POST 有效

c# - WPF 中 IP 地址的文本框验证

c# - 模块类型加载异常 : Failed to load type for module

javascript - 我想在我的参数编辑器中使用正则表达式来验证标志和值

javascript - W3 使用 1 行 JavaScript 代码验证 html 错误

c# - 如何将youtube视频嵌入WPF MediaElement并保存视频?