Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

c# - Get the "Key" for a strongly typed model in the controller

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.ValidationMessageFor(model => model.Email)

Whats the equivalent code to get the Key name to add in the controller so it attaches to this ValidationMessage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...