开发者

How to generate field names for model state dictionary?

The new helper methods EditorFor, TextBoxFor are very cool in avoiding hard coded field names in views.

I'm writing validation functions where services validate complex model data. If there is an error with a field the service should push an error for this field into the modelstate dictionary.

Is there an helper method with generates the complete model name?

EDIT:

Samplemodel:

class CustomModel {
  public InnerModel Inner { get; set; }
}
class InnerModel {
  public String Field1 { get; set; }
  public SomethingMoreToValidate[] More { get; set; }
}
class SomethingMoreToValidate {
  public int A { get; set; }
  public int B { get; set; }
}

The input field for InnerModel.SomethingMoreToValidate[0].A in the view has the name "InnerModel.SomethingMoreToValidate[0].A". To bind the model state errors to the field, I have to put the errors with this name into the ModelStateDictionary.

In the View displaying the InnerModel data, I can write:

Html.EditorFor(m => m.SomethingMoreToValidate[0].A);

If a property is renamed, compiler warns me. In the valid开发者_开发问答ating controller or service class I have to write:

ModelState.AddModelError(
  "InnerModel.SomethingMoreToValidate[0].A", 
  "There is a problem with this field");

If a property is renamed, there is no feedback if I have no other checks like unittests. I would like to write:

ModelState.AddModelErrorFor(
  m => m.InnerModel.SomethingMoreToValidate[0].A, 
  "There is a problem with this field")


You could write a helper using the GetExpressionText method:

public static string GetExpressionText<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
    return ExpressionHelper.GetExpressionText(expression);
}

and then:

var expression = GetExpressionText<MyViewModel, string>(
    x => x.InnerModel.SomethingMoreToValidate[0].A
);

ModelState.AddModelErrorFor(expression, "There is a problem with this field");

This being said, you should obviously have unit tests in a properly written application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜