How to override global ModelBinder for specific post action mvc5

你离开我真会死。 提交于 2019-12-11 04:42:23

问题


I have applied a global ModelBinder for int arrays as below:

public class IntArrayModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,
                                     ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (string.IsNullOrEmpty(value?.AttemptedValue))
        {
            return null;
        }

        try
        {

            return value
                .AttemptedValue
                .Split(',')
                .Select(int.Parse)
                .ToArray();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return null;
        }
    }
}

Then register this IntArrayModelBinder in global.asax.cs as below

ModelBinders.Binders.Add(typeof(int[]), new IntArrayModelBinder());

Now I want to ignore this model binder in a specific post action and use the default binding.

My ViewModel is

public class AddListViewModel
{
    public string[] SelectedNames { get; set; }
    public int[] SelectedList { get; set; }
}

And my action:

[HttpPost]
public JsonResult AddInList(AddListViewModel vm)
{
    //  code here
}

But the result of SelectedList is always null. Binding does not work. If I disable the global custom binding then the binding works fine.

I tried to specify the DefaultModelBinder as below, but no success

[HttpPost]
public JsonResult AddCompaniesInList(
    [ModelBinder(typeof(DefaultModelBinder))]AddListViewModel vm)
{}

I even created another custom default binder to add the action. But it still seems that default binder overrides my action binder and the result is always null.

How can I ignore default global binding for a specific action?

来源:https://stackoverflow.com/questions/45379040/how-to-override-global-modelbinder-for-specific-post-action-mvc5

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