asp.net-mvc-4 - 在选中的复选框中发布表单时,ModelState 无效

标签 asp.net-mvc-4 asp.net-web-api

我遇到以下问题:如果我通过 AJAX 向 api Controller 提交一个包含复选框中选中值的表单,则 ModelState 对象表示它无效。

先决条件:

  • Visual Studio 2012
  • ASP.NET MVC 4 最终版
  • 最新的 jQuery 和 jQuery 非侵入式验证内容(版本 1.8.2 和 1.9.0.1)

  • 重现步骤:
  • 为表单创建了一个 ViewModel,包含 bool 字段:
    public class CheckboxViewModel
    {
    [Display(Name="Test checkbox")]
    public bool TestCheckbox { get; set; }
    }
    
  • Created controller action that simply prepares ViewModel and renders form:
    public ActionResult Index()
    {
        return View(new CheckboxViewModel());
    }
    
  • Created a view with form
    @using (Ajax.BeginForm("Post", "api/Values", null, new AjaxOptions { HttpMethod = "POST" }, new { id = "form" }))
    {
        @Html.ValidationSummary(true)
        @Html.LabelFor(model => model.TestCheckbox)
        @Html.EditorFor(model => model.TestCheckbox)
        @Html.ValidationMessageFor(model => model.TestCheckbox)
        <input type="submit" value="Submit" />
    }
    
  • Created Web API action that checks if modelstate is valid and return status code 200,otherwise 400:
    public HttpResponseMessage Post(CheckboxViewModel model)
    {
        if (!ModelState.IsValid)
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  • I've done some googling and I know that editor for checkbox renders additional hidden field, but it seems to be ok and is needed for model binding. So, when I uncheck checkbox and submit form everything works fine, server responds with status 200, thanks to hidden field, I suppose. However, when I make checkbox checked and submit form, server responds with status 400, meaning that ModelState is in invalid state. ModelState in this case contains error with empty ErrorMessage and following Exception message:

    {System.InvalidOperationException: The parameter conversion from type 'System.Collections.Generic.List`1[System.String]' to type 'System.Boolean' failed because no type converter can convert between these types.
       в System.Web.Http.ValueProviders.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
       в System.Web.Http.ValueProviders.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)
       в System.Web.Http.ValueProviders.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)
       в System.Web.Http.ValueProviders.ValueProviderResult.ConvertTo(Type type)
       в System.Web.Http.ModelBinding.Binders.TypeConverterModelBinder.BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)}
    

    I have no idea how to handle this properly. Should I create custom model binder? Or am I missing something? Any help would be appreciated. Thanks.

    I've created solution that reproduces my issue.

    UPDATE: I've figured out that form actually contains values TestCheckbox: trueTestCheckbox:false ,所以我认为这可能会影响活页夹并引发异常。仍然没有选择如何解决这个问题。

    最佳答案

    我遇到了同样的问题,使用 JavaScript 将表单发送到 Web API。这是您可以用来解决问题的基本修复程序。我知道这有点简单甚至丑陋 - 如果您有很多复选框,则不太实用。但是,这个想法很简单,可以轻松扩展以满足您的要求。

    在发布表单之前添加此内容(使用 jQuery):

    if ($('[name="MyCheckbox"]:checked').length > 0)
        $('[name="MyCheckbox"]:hidden').detach();
    else if ($('[name="MyCheckbox"]:hidden').length < 1)
        $('#myForm').append('<input type="hidden" name="MyCheckbox" value="false" />');
    
    // Etc...
    $.ajax({ });
    

    因此,如果选中复选框,则删除隐藏字段,如果未选中复选框且隐藏字段已被删除,则添加它。

    看到这个 fiddle :http://jsfiddle.net/Hsfdg/

    关于asp.net-mvc-4 - 在选中的复选框中发布表单时,ModelState 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12807170/

    相关文章:

    asp.net-web-api - Web API - 支持的动词吗?

    asp.net-mvc - MVC Areas、MvcCodeRouting、两者,还是其他架构?

    asp.net-mvc-4 - session 在 Azure 中如何工作

    c# - Controller 单元测试期间未启用角色管理器功能错误

    asp.net-web-api - OData V4修改服务器端$filter

    javascript - 如何获取 Fitbit 排行榜以进行比赛

    c# - OData v4 自定义函数

    asp.net-web-api - WebAPI HttpContext 在ContinueWith() => 里面为空

    asp.net - 流式上传时获取上传文件的名称

    asp.net-mvc - 为什么 ASP.NET MVC Controller 类需要公开?