问题
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