ASP.NET MVC WebGrid is not properly passing current parameters to the pagination links in a particular situation

六眼飞鱼酱① 提交于 2019-12-06 08:10:33

In case anybody else is suffering from the issue described, you can work around this using a custom model binder like this:

public class WebgridCheckboxWorkaroundModelBinder : DefaultModelBinder
{
    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.PropertyType == typeof (Boolean))
        {
            var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
            if (value.AttemptedValue == "true,false")
            {
                PropertyInfo prop = bindingContext.Model.GetType().GetProperty(propertyDescriptor.Name, BindingFlags.Public | BindingFlags.Instance);
                if (null != prop && prop.CanWrite)
                {
                    prop.SetValue(bindingContext.Model, true, null);
                }
                return;
            }
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
}

An alternative to inheriting from the DefaultModelBinder would be to implement the IModelBinder interface specifically for nullable boolean values.

internal class BooleanModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Get the raw attempted value from the value provider using the ModelName
        var param = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (param != null)
        {
            var value = param.AttemptedValue;
            return value == "true,false";
        }
        return false;
    }
}

You can then add the model binding to the Global.asax or add it to the parameter like so:

public ActionResult GridRequests([ModelBinder(typeof(BooleanModelBinder))]bool? IsShowDenied, GridSortOptions sort, int? page)
{
    ...
}

For those who would like to implement the custom model binder in Dan's solution, but aren't sure how.

You have to register the model binder in the Global.asax file:

protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(HomeViewModel), new WebgridCheckboxWorkaroundModelBinder());
    }

And also specify its use in your action:

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