How to specify error member key in ASP.NET MVC CustomValidation?

I am trying to add CustomValidation and make it a return error for

Html.ValidationMessageFor (m => m.SubleaseCompany)

[CustomValidation(typeof(CreateSpaceModelValidation), "ValidateCreateSpaceModel")] public class CreateSpaceModel { public Building Building { get; set; } public Space Space { get; set; } public string SubleaseCompany { get; set; } } public class CreateSpaceModelValidation { public static ValidationResult ValidateCreateSpaceModel(CreateSpaceModel model) { return new ValidationResult("You should specify Sublease Contact", new[] { "SubleaseCompany" }).; } } 

I use the second argument to the ValidationResult (memberNames) constructor, but this does not work.

+7
validation asp.net-mvc
source share
1 answer

It looks like the MVC team never performed the functions for the MemberNames parameter. See the next exercise from ... http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

In some situations, you may be tempted to use the second ValidationResult overload constructor, which is taken in IEnumerable of member names. For example, you may decide that you want to display an error message in both fields: compared, so you change the code to this:

 return new ValidationResult( FormatErrorMessage(validationContext.DisplayName), 

new [] {validationContext.MemberName, OtherProperty});

If you run your code, you will find there is absolutely no difference. This is because although this overload is present and appears to be used elsewhere in the .NET environment, the MVC structure completely ignores ValidationResult.MemberNames.

+8
source share

All Articles