Revalidating a modified ViewModel within a controller method?

我与影子孤独终老i 提交于 2019-11-28 05:12:15
counsellorben

Once you have removed the offending item(s), clear the ModelState and validate again, like so:

ModelState.Clear();
TryValidateModel(crew);  // assumes the model being passed is named "crew"

Note: Be carefull when use TryValidateModel method because this method does not validate nested object of model (As mentioned by @Merenzo).

Late to the game, but still: I was also looking for a way to validate model after doing some tweaks to it (more precisely - to the items of its nested collection) - and TryValidateModel didn't work for me, as it doesn't process nested objects.

Finally, I settled with custom model binder:

public class MyItemModelBinder : DefaultModelBinder
{
    protected override void OnModelUpdated(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(MyItemModel))
        {
            MyItemModel item = (MyItemModel)bindingContext.Model;
            //do required tweaks on model here 
            //(I needed to load some additional data from DB)
        }
        //validation code will be called here, in OnModelUpdated implementation
        base.OnModelUpdated(controllerContext, bindingContext);
    }
}

on the model class:

[ModelBinder(typeof(MyItemModelBinder))]
public class MyItemModel : IValidatableObject
{
    //...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!