ValidationMessageFor与AddModelError在一起(密钥,消息)。什么关键? [英] ValidationMessageFor together with AddModelError(key, message). Whats the key?

查看:131
本文介绍了ValidationMessageFor与AddModelError在一起(密钥,消息)。什么关键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个客户端和服务器端验证了一定的ViewModel属性。

I am developing a client-side and server-side validation for a certain viewModel property.

在我把这个 .cshtml 文件:

@Html.DropDownListFor(model => model.EntityType.ParentId, Model.ParentTypeList, "")
@Html.ValidationMessageFor(model => model.EntityType.ParentId)

在控制器的业务验证

catch (BusinessException e)
{
    ModelState.AddModelError("EntityType.ParentId", Messages.CircularReference);
}

如预期上述工程:如果一个异常被捕获,后面会出现一个DropDownList的消息

The above works as expected: if an exception is caught, the message appears next to the dropdownlist.

不过,我觉得这种方式不是很优雅。在 CSHTML ,我用一个方法来产生所有有关验证所需的信息。在控制器中,我必须知道确切的密钥字符串,并使用它。

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.

是不是有这样做的更好的办法?

Isn't there a better way of doing this?

感谢您。

推荐答案

您可以写,将采取一个lambda前pression的关键,而不是一个字符串的扩展方法:

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);
    }
}

,然后用这个方法:

and then use this method:

catch (BusinessException e)
{
    ModelState.AddModelError<MyViewModel, int>(
        x => x.EntityType.ParentId, 
        Messages.CircularReference
    );
}

这篇关于ValidationMessageFor与AddModelError在一起(密钥,消息)。什么关键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆