Get the “Key” for a strongly typed model in the controller

后端 未结 2 1788
面向向阳花
面向向阳花 2020-12-17 03:06

So I am trying to do get the key for a model object in the controller so that I can add a AddModelError to it.

In my view I use

@Html.V         


        
相关标签:
2条回答
  • 2020-12-17 03:22
    ModelState.AddModelError("Email", "the email is invalid");
    

    But usually that's not something you should be doing manually in your controller but you should be using a validator. For example you could decorate this Email property with some validation data annotation attribute or if you are like me use FluentValidation.NET => this way you shouldn't be asking yourself questions about keys but focus on the actual validation logic.

    0 讨论(0)
  • 2020-12-17 03:36

    You can use an extension that does the same as the HtmlHelpers, and that will work for nested properties:

    public static class ModelStateExtensions
    {
      public static void AddModelError<TModel>(this ModelStateDictionary dictionary, Expression<Func<TModel, object>> expression, string errorMessage)
      {
        dictionary.AddModelError(ExpressionHelper.GetExpressionText(expression), errorMessage);
      }
    }
    

    So you can use it like this:

    ModelState.AddModelError<TModel>(i => i.Person.Name, "test");
    

    equivalent to

    ModelState.AddModelError("Person.Name", "test");
    

    It will generate the same Id as the Html. In the MVC source they do some extra sanitizing, but with normal names that shouldn't be a problem.

    0 讨论(0)
提交回复
热议问题