我已经设法让这个工作达到一定程度,所以这是我的解决方案供其他人评估。
需要注意的一点是,无法实现完整的解决方案,因为我无法获得Modelmetadata
在 - 的里面StringValidation.IsValid()
属性。我在这里遇到的具体问题是我可以获取元数据,但是我无法获取PropertyName
从中,仅DisplayName
。那里有多种选择,但事实上我的一些房产具有相同的DisplayName
意味着我无法确定ProprtyName
是我实际验证的那个。
这是代码ValidationAttribute
:
public class StringValidationAttribute : ValidationAttribute, IClientValidatable, IMetadataAware {
private bool _uppercase;
public StringValidationAttribute(bool uppercase = false) {
_uppercase = uppercase;
}
...
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["Uppercase"] = _uppercase;
}
}
然后我创建了一个新的IModelBinder
执行:
public class StringBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (result == null)
return null;
if (bindingContext.ModelMetadata.AdditionalValues.ContainsKey("Uppercase")) {
if ((bool)bindingContext.ModelMetadata.AdditionalValues["Uppercase"]])
return result.AttemptedValue.ToUpper();
}
return result.AttemptedValue;
}
}
并在我的中注册了Global.asax
file:
ModelBinders.Binders.Add(typeof(string), new StringBinder());
到目前为止的代码将导致任何进入 MVC 的字符串输入转换为大写(如果有)StringValidationAttribute
附加到模型上,以及已设置大写指示器的位置。
接下来,为了实现我让 html 表单也变成大写的愿望,我实现了一个新的EditorTemplate
named string.cshtml
。在这个视图中我添加了:
RouteValueDictionary htmlAttributes = new RouteValueDictionary();
if ((bool)ViewData.ModelMetadata.AdditionalValues["Uppercase"]) {
htmlAttributes.Add("class", "Uppercase");
}
@Html.TextBox("", Model, htmlAttributes)
与CSS一样;
.Uppercase {
text-transform: uppercase;
}
希望这篇文章可以帮助其他人。