在特定情况下,ASP.NET MVC WebGrid未正确地将当前参数传递给分页链接

And*_*ena 2 .net webgrid asp.net-mvc-3

WebGrid 分页链接在所有情况下都能正常工作,除了一个(我注意到).

当您CheckBoxFor在MVC中使用时,它会为同一个字段创建一个input[type=hidden]和一个input[type=check-box],以便它可以处理状态.因此,如果您有一个名为X并在GET方法中提交表单的字段,您将得到如下URL:

http://foo.com?X=false&X=true

默认的模型绑定器可以理解这些多个实例os X并找出它的值.

当您尝试对其进行分页时会发生此问题WebGrid.它的行为是尝试捕获当前请求参数并在分页链接中进行修复.但是,由于不止一个X,它将通过X=false,true而不是预期的X=falseX=false&X=true

这是一个问题因为X=false,true无法正确绑定.在操作开始之前,它将在模型绑定器中触发异常.

有没有办法可以解决它?

编辑:

这似乎是一个非常具体的问题,但事实并非如此.几乎每个带有复选框的搜索表单都会破坏WebGrid的分页.(如果您正在使用GET)

编辑2:

我认为我唯一的选择是:

  • 构建我自己的WebGrid寻呼机,它更灵活地传递分页链接的参数
  • 构建我自己的布尔模型绑定器,它理解false,true为有效

Dan*_*yan 5

如果其他人遇到了所描述的问题,您可以使用这样的自定义模型绑定器解决此问题:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)