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)
在Controller中用于业务验证
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屋!