ValidationMessageFor together with AddModelError(key, message). What's the key?

前端 未结 3 1804
暖寄归人
暖寄归人 2020-12-15 07:57

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

In the .cshtml file I put this:

@Html.DropDow         


        
3条回答
  •  太阳男子
    2020-12-15 08:32

    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(
            this ModelStateDictionary modelState, 
            Expression> ex, 
            string message
        )
        {
            var key = ExpressionHelper.GetExpressionText(ex);
            modelState.AddModelError(key, message);
        }
    }
    

    and then use this method:

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

提交回复
热议问题