ModelState中发布选中的复选框中的窗体时无效 [英] ModelState is invalid when posting a form within checked checkbox

查看:188
本文介绍了ModelState中发布选中的复选框中的窗体时无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:如果我提交包含检查值复选框,通过AJAX API控制器形式,对象的ModelState说这是无效的。

I'm experiencing following issue: if I submit a form that contains checked value in checkbox to the api controller via AJAX, ModelState object says it's invalid.

prerequisites:

Prerequisites:


  1. 的Visual Studio 2012

  2. ASP.NET MVC 4决赛

  3. 最新的jQuery和jQuery不引人注目的验证的东西(版本1.8.2和1.9.0.1)

重现步骤:


  1. 创建一个视图模型的形式,包含布尔字段:
  1. Created a ViewModel for form, containing Boolean field:

public class CheckboxViewModel
{
[Display(Name="Test checkbox")]
public bool TestCheckbox { get; set; }
}


  • 创建控制器动作,仅仅prepares视图模型和呈现形式:

  • 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" />
    }
    


  • 来检查,如果ModelState中是有效的,返回状态code 200,否则400创建的Web API操作:

  • 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);
    }
    


  • 我做了一些谷歌上搜索,我知道编辑器复选框呈现额外的隐藏字段,但它似乎是确定,并需要对模型绑定。
    所以,当我取消复选框,并提交表单一切正常,服务器状态200响应,这要归功于隐藏字段,我想。然而,当我做检查的复选框,并提交表单,服务器状态400响应,这意味着ModelState中处于无效状态。的ModelState在这种情况下,包含空的ErrorMessage和下面的异常信息的错误:

    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)}
    

    我不知道如何正确地处理这个问题。我应该创建自定义的模型绑定?还是我失去了一些东西?
    任何帮助将是AP preciated。谢谢你。

    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.

    更新:我已经想通了,形式实际上包含的值 TestCheckbox:真正的 TestCheckbox:假,所以我觉得这也许某种影响粘合剂和它抛出一个异常。仍然没有选择如何解决此。

    UPDATE: I've figured out that form actually contains values TestCheckbox: true and TestCheckbox:false, so I think this maybe some kind affects binder and it throws an exception. Still have no options how to workaround this.

    推荐答案

    我遇到了同样的问题,发送形式与JavaScript的Web API。这里是你可以用它来解决此问题的基本修正。我知道这是一种简单的,甚至丑陋的 - 如果你有很多的复选框,并不太实用。然而,这个想法很简单,可以很容易地进行扩展,以满足您的要求。

    I ran into the same problem sending a form to a Web API with JavaScript. Here is a basic fix you can use to work around the problem. I know it's kind of simplistic or even ugly - and not very practical if you have lots of checkboxes. However, the idea is simple and could easily be extended to meet your requirements.

    将此您发布表单之前(使用jQuery):

    Add this before you post the form (using 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({ });
    

    所以,你删除隐藏字段如果复选框被选中,并添加它,如果未选中的复选框,并隐藏字段已经被删除了。

    So you remove the hidden field if the checkbox is checked, and you add it if the checkbox isn't checked and the hidden field has already been deleted.

    看到这个小提琴: http://jsfiddle.net/Hsfdg/

    这篇关于ModelState中发布选中的复选框中的窗体时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆