Validation Attribute get triggered two times

我是研究僧i 提交于 2019-12-11 03:45:36

问题


In my MVC3 application I have the model ( not important properties deleted ):

public class AccountViewModel
{
    [StringLength(65)]
    public string Property1 { get; set; }

    [StringLength(65)]
    public string Property2 { get; set; }
}

The problem is when an action is submited validation attribute called twice, and I can get 4 errors in summary, instead of 2:

'Property1' length must be less than 65 characters
'Property1' length must be less than 65 characters
'Property2' length must be less than 65 characters
'Property2' length must be less than 65 characters

I dont use Validate method in my controller's code. The problem appears also with my custom attributes, but its not happens with Required attribute. Also I have to note that ctor of the custom attributes also called twice

My action

[HttpPost]
public ActionResult CreateOrEdit(AccountViewModel model) {

    if (!ModelState.IsValid) {
        return View("Edit", model);
    }

    try {
        _accountService.InsertOrUpdate(model);

    }
    catch (Exception ee) {
        ModelState.AddModelError("", ee.Message);
        return View("Edit", model);
    }

    return RedirectToAction("Index");
}

On View I render my errors using:

@{
    var errors = ViewData.ModelState.Errors();
    <div class="alert alert-block alert-error @(errors.Count == 0 ? "hide" : "")" > 
    <h4 class="alert-heading"> You got an error!</h4> 
    <ul>
        @foreach (var error in errors) {
            <li>@error</li>
        }
    </ul>
    </div>
}

And I double re-check once more that ViewData.ModelState already contains errors twice.


回答1:


The problem was in integrating Ninject. If you use Ninject.MVC package ( I use version 3 ) it registers his own ModelValidationProvider while initializing and removes the old one:

In Ninject.Web.Mvc.MvcModule

this.Kernel.Bind<ModelValidatorProvider>().To<NinjectDataAnnotationsModelValidatorProvider>();

In Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin:

public void Start()
{
    ModelValidatorProviders.Providers.Remove(ModelValidatorProviders.Providers.OfType<DataAnnotationsModelValidatorProvider>().Single());
    DependencyResolver.SetResolver(this.CreateDependencyResolver());
    RemoveDefaultAttributeFilterProvider();
}

So, rather than creating my own implementation of IDependencyResolver ( Ninject Kernel wrapper ) I followed this tutorial or you should remove Ninject.MVC package and remove its binaries from the bin folder.



来源:https://stackoverflow.com/questions/10129669/validation-attribute-get-triggered-two-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!