Question

*First Post

I have a JQuery error handler for my Ajax posts that I must use, it appends an error to the html based on the field name for that element like this

$(document).ready(function () {
function myHandler(e, error) {
    var tag = "";
    if (error.Success == true) { $('.field-validation-error').remove(); return; } // if success remove old validation and don't continue
    if (error.Success == false) { $('.field-validation-error').remove(); } // if success remove old validation and continue
    for (i = 0; i < error.Errors.length; i++) {
        var t = error.Errors[i];
        //get error key and assign it to id
        tag = t.Key;
        //clear down any existing json-validation
        for (j = 0; j < t.Value.length; j++) {
            //this part assumes that our error key is the same as our inputs name
            $('<span class="field-validation-error">' + t.Value[j].ErrorMessage + '</span>').insertAfter('input[name="' + tag + '"], textarea[name="' + tag + '"], select[name="' + tag + '"], span[name="' + tag + '"]');
        }
    }
}


$.subscribe("/******/errors", myHandler);

});

This works perfectly out of the box with our fluent validation setup until I try to add a custom modelstate error at controller level like so:

foreach (var item in model.Locations)
        {
            var cityRepos = new CityRepository(NhSession);
            var cityItem = cityRepos.GetAll().FirstOrDefault(o => o.Country.Id == item.CountryID && o.Name == item.City);
            if (cityItem == null)
                item.City
                ModelState.AddModelError("City", string.Format(@"The city ""{0}"" was not found, please ensure you have spelt it correctly. TODO: add a mail to link here with city not found subject", item.City));
        }

the problem is that the modelstate error needs to be attached to the html field name not my magic string "City". The html name property is MVC Generated and looks something like this:

 name="Locations[0].City"

I have encountered this problem in a html helper before and used the method:

.GetFullHtmlFieldName(
                                                 ExpressionHelper.GetExpressionText(propertySelector)
                                             );

which resolved my problem in that case.

My question is can I use this method on my model property in an MVC post action to obtain the html name property it has come from?

Thanks in advance

Était-ce utile?

La solution

ok so it's not ideal but I have implemented this Helper method until I can find a better solution that doesn't involve magic strings:

public static class ModelStateErrorHelper
{
    public static string CreateNameValidationAttribute(string collectionName, int index, string propertyName)
    {
        string template = "{0}[{1}].{2}";
        return string.Format(template, collectionName, index.ToString(), propertyName);
    }

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top