【问题标题】:How can I get ASP.NET Core WebAPI method to bind to a model's boolean field?如何让 ASP.NET Core WebAPI 方法绑定到模型的布尔字段?
【发布时间】: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&amp;name=Joe&amp;agree=on)。在接收端,我的 API 方法如下所示:

[HttpPost("subscribe", Name = "Subscribe")]
public IActionResult Subscribe(Subscription subscription) {
    if(!ModelState.IsValid) {
        return BadRequest();
    }
    SubscriptionRepository.Create(subscription);
    return Ok();
}

Subscription 是一个 POCO,其中一些 stringbool 类型对应于正在提交的表单字段,例如:

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


【解决方案1】:

尝试使用以下方法捕获错误:

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, examine the list with Exceptions.
}

【讨论】:

    【解决方案2】:

    如果复选框有value 属性,它将在提交表单时发布(并且选中复选框)。如果未选中复选框并且您尝试提交表单,则不会提交该项目,因此您的 boolean 属性将获得默认值 false

    如果复选框没有值属性,那么当您选中复选框并提交表单时,将发送值"on"(这就是发生在您身上的事情),如果未选中复选框,则不会发送该元素。

    因此,只需将 value="true" 添加到呈现复选框的 html 中即可。

    <form id="SubscriptionForm">
        Email: <input type="email" name="email" /><br>
        Name: <input type="text" name="name" /><br>
        <input type="checkbox" value="true" name="agree" /> I wish to subscribe
        <input id="submit" type="submit" />
    </form>
    

    另外你需要确保你的属性是public,否则模型绑定器将无法设置这些值!

    public class Subscription 
    {
       public string Email { get; set; }
       public  string Name { get; set; }
       public  bool Agree { get; set; }
    }
    

    【讨论】:

    • 谢谢。我知道复选框是如何工作的,但没想到 ASP.NET 愚蠢到无法理解默认的复选框真值,自复选框出现以来就一直存在! :)
    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多