Monday, October 28, 2013

How to fix obtrusive JavaScript validation not working in ASP.NET MVC?

There are reasons to cause this problem. For my case is I make a new class inherit from RequriedAtribute, but not resister in the Application_Start event.

protected void Application_Start()
{
      DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(i18n.DataAnnotations.RequiredAttribute), typeof(RequiredAttributeAdapter));
}

namespace i18n.DataAnnotations
{
    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, ILocalizing
    {
        private readonly I18NSession _session;

        public RequiredAttribute()
        {
            _session = new I18NSession();   
        }

        public virtual IHtmlString _(string text)
        {
            return new HtmlString(_session.GetText(HttpContext.Current, text));
        }

        public virtual string TT(string text)
        {
            return _session.GetText(HttpContext.Current, text);
        }

        public override string FormatErrorMessage(string name)
        {
            var formatted = base.FormatErrorMessage(name);
            return _(formatted).ToHtmlString();
        }
    }
}