lng
lng

Reputation: 805

Avoiding string literals when using ModelState.AddModelError

In my MVC 5 app when I want to return validation error for the form values I use this pattern in the Controller:

ModelState.AddModelError("PropertyName", "Validation Message");

Is there a recommended practice that does not use string literal in the Controller for property name?

I am using .Net 4.5 and I would rather not upgrade to .Net 4.6. I am using Visual Studio 2013 and would rather not upgrade to Visual Studio 2015.

Upvotes: 1

Views: 143

Answers (2)

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

I think it can be achieved like this:

1) Define a base controller that inherits Controller:

class BaseController<TCtr> : Controller

2) Have your actual control inherit BaseController instead of Controller:

class YourController : BaseController<TCtr>

3) Define the following function in your BaseController:

protected virtual void AddModelError<TProp>(Expression<Func<TCtr, TProp>> expression, String message)
    {
        var prop = (MemberExpression)expression.Body;
        ModelState.AddModelError(prop.Member.Name, message);
    }

This allows you to write something like this in your controller:

AddModelError(ctrl => SomeProperty, "Validation failed");

Upvotes: 0

RB.
RB.

Reputation: 37202

C# 6 introduces the nameof operator, so you can do the following:

ModelState.AddModelError(nameof(this.PropertyName), "Validation Message");

This requires Visual Studio 2015 though.

Upvotes: 2

Related Questions