Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the "Key" for a strongly typed model in the controller

Tags:

c#

asp.net-mvc

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.

like image 300
John Mitchell Avatar asked Aug 17 '12 17:08

John Mitchell


People also ask

What is @model in Cshtml?

The @model directive allows access to the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object: CSHTML Copy.

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

What is a strongly typed view in MVC?

A Strongly Typed view means it has a ViewModel associated to it that the controller is passing to it and all the elements in that View can use those ViewModel propertiesYou can have strongly typed partials as well.


2 Answers

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.

like image 125
John Landheer Avatar answered Oct 18 '22 09:10

John Landheer


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.

like image 38
Darin Dimitrov Avatar answered Oct 18 '22 10:10

Darin Dimitrov