我遇到以下问题:如果我通过 AJAX 向 api Controller 提交一个包含复选框中选中值的表单,则 ModelState 对象表示它无效。
先决条件:
重现步骤:
public class CheckboxViewModel
{
[Display(Name="Test checkbox")]
public bool TestCheckbox { get; set; }
}
public ActionResult Index()
{
return View(new CheckboxViewModel());
}
@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" />
}
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: true
和 TestCheckbox: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/