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

前端 未结 3 1742
暖寄归人
暖寄归人 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:13

    You want the validation to happen at both the client and server side and also you looking for an elegant solution then why can try creating a custom ValidationAttribute.

    0 讨论(0)
  • 2020-12-15 08:24

    I follow @Darin Dimitrov solution but i want to avoid <MyViewModel, int> so I used some different way but for that you need MyViewModel object variable.

    public static class ModelStateExtensions
    {
        public static void AddModelError<TModel, TProperty>(this TModel source,        
                                                        Expression<Func<TModel, TProperty>> ex, 
                                                        string message,
                                                        ModelStateDictionary modelState)
        {
            var key = System.Web.Mvc.ExpressionHelper.GetExpressionText(ex);
            modelState.AddModelError(key, message);
        }
    }
    

    How to Use:

    catch (BusinessException e)
    {
        objMyViewModel.AddModelError(x => x.EntityType.ParentId, 
                                     Messages.CircularReference,
                                     ModelState);
    }
    
    0 讨论(0)
  • 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<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
        );
    }
    
    0 讨论(0)
提交回复
热议问题