1

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.

RB.
  • 36,301
  • 12
  • 91
  • 131
lng
  • 805
  • 1
  • 11
  • 31

2 Answers2

2

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.

RB.
  • 36,301
  • 12
  • 91
  • 131
  • Thanks for your quick response RB. However I am using .net 4.5 and I would rather not upgrade to .net 4.6. I updated the question to include this information. – lng Dec 21 '15 at 16:48
  • It is a C# 6 compiler feature, not a .NET 4.6 feature. You can run code using the nameof operator on .NET 4.0 onwards (I'm pretty sure you could target any version of the framework, but I happen to have tested .NET 4.0...!) – RB. Dec 21 '15 at 16:50
  • Thanks again. I am also using Visual Studio 2013 and would rather not upgrade to Visual Studio 2015. – lng Dec 21 '15 at 16:54
0

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");
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164