加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何获取模型属性的id以与MVC3中的自定义IClientValidatab

发布时间:2020-12-16 01:46:21 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个自定义验证属性,该属性将有条件地要求基于模型的布尔属性的字段. 我有我的属性实现IClientValidatable.我有要检查的属性的名称,但我不知道如何获取目标属性的客户端ID. public IEnumerableModelClientValidationRule GetClientValidationR
我正在尝试编写一个自定义验证属性,该属性将有条件地要求基于模型的布尔属性的字段.

我有我的属性实现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: https://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;
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读