【发布时间】:2017-05-16 01:18:08
【问题描述】:
我有一个使用 JQuery 发布到我的 WebAPI 端点的表单:
<form>
Email: <input type="email" name="email" /><br>
Name: <input type="text" name="name" /><br>
<input type="checkbox" name="agree" /> I wish to subscribe
</form>
...
function Subscribe() {
$.ajax({
url: "api/Subscription/subscribe",
method: "POST",
data: $("#SubscriptionForm").serialize()
})
.done(function() { alert("yay!"; })
.fail(function() { alert(":("); });
}
正如预期的那样,以application/x-www-form-urlencoded 形式提交表单(例如email=me@domain.com&name=Joe&agree=on)。在接收端,我的 API 方法如下所示:
[HttpPost("subscribe", Name = "Subscribe")]
public IActionResult Subscribe(Subscription subscription) {
if(!ModelState.IsValid) {
return BadRequest();
}
SubscriptionRepository.Create(subscription);
return Ok();
}
Subscription 是一个 POCO,其中一些 string 和 bool 类型对应于正在提交的表单字段,例如:
public class Subscription {
string Email { get; set; }
string Name { get; set; }
bool Agree { get; set; }
}
问题
只要没有选中表单上的复选框,WebAPI 方法就能够成功地将其他表单字段绑定到模型。但是当至少有一个复选框被选中时,ModelState.IsValid 返回 false。
我怀疑 WebAPI 无法将传递给选定复选框的 on 值转换为 bool。这似乎是一个非常基本的普遍需求,所以我错过了一些简单的东西吗?
【问题讨论】:
-
在复选框的 HTML 中添加
value="True"属性。
标签: jquery asp.net-web-api asp.net-core asp.net-core-mvc