ValidationMessageFor 与 AddModelError(key, message) 一起使用.关键是什么? [英] ValidationMessageFor together with AddModelError(key, message). What's the key?
问题描述
我正在为某个 viewModel 属性开发客户端和服务器端验证.
I am developing a client-side and server-side validation for a certain viewModel property.
在 .cshtml
文件中,我把这个:
In the .cshtml
file I put this:
@Html.DropDownListFor(model => model.EntityType.ParentId, Model.ParentTypeList, "")
@Html.ValidationMessageFor(model => model.EntityType.ParentId)
在用于业务验证的控制器中
In the Controller for the business validation
catch (BusinessException e)
{
ModelState.AddModelError("EntityType.ParentId", Messages.CircularReference);
}
以上按预期工作:如果捕获到异常,消息会出现在下拉列表旁边.
The above works as expected: if an exception is caught, the message appears next to the dropdownlist.
但是,我发现这种方式不是很优雅.在 cshtml
中,我使用一种方法来生成有关验证的所有必需信息.在控制器中,我必须知道确切的 Key 字符串并使用它.
However, I find that this way is not very elegant. In the cshtml
, I use a method to generate all the required information about the validation. In the controller, I must know the exact Key string and use it.
没有更好的方法吗?
推荐答案
您可以编写一个扩展方法,该方法将对键采用 lambda 表达式而不是字符串:
You could write an extension method that will take a lambda expression for the key instead of a string:
public static class ModelStateExtensions
{
public static void AddModelError<TModel, TProperty>(
this ModelStateDictionary modelState,
Expression<Func<TModel, TProperty>> ex,
string message
)
{
var key = ExpressionHelper.GetExpressionText(ex);
modelState.AddModelError(key, message);
}
}
然后使用这个方法:
catch (BusinessException e)
{
ModelState.AddModelError<MyViewModel, int>(
x => x.EntityType.ParentId,
Messages.CircularReference
);
}
这篇关于ValidationMessageFor 与 AddModelError(key, message) 一起使用.关键是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!