我正在尝试编写一个自定义验证属性,该属性将有条件地需要基于模型的 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/