加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ValidationMessage与AddModelError(key,message)一起使用.

发布时间:2020-12-15 17:38:39 所属栏目:百科 来源:网络整理
导读:我正在为某个viewModel属性开发客户端和服务器端验证. 在.cshtml文件中,我把这个: @Html.DropDownListFor(model = model.EntityType.ParentId,Model.ParentTypeList,"")@Html.ValidationMessageFor(model = model.EntityType.ParentId) 在控制器中进行业务
我正在为某个viewModel属性开发客户端和服务器端验证.

在.cshtml文件中,我把这个:

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

在控制器中进行业务验证

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

以上工作如预期:如果捕获到异常,该消息将出现在下拉列表旁边.

但是,我觉得这样做不是很优雅.在cshtml中,我使用一种方法生成有关验证的所有必需信息.在控制器中,我必须知道确切的Key字符串并使用它.

是不是有更好的方法呢?

解决方法

您可以编写一个扩展方法,该方法将为键而不是字符串使用lambda表达式:
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
    );
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读