ASP.NET Core CheckBox 总是 returns false 值

ASP.NET Core CheckBox always returns false value

有谁知道为什么我在更新表单时总是得到错误的值?我尝试将 (value="false") 放入复选框,但仍然无效。感谢您的帮助!

<form asp-controller="Weather" asp-action="Update" method="POST">
    <tr>
        <td>@city.City</td>
        <td><input type="number" name="cityId" value="@city.Id" hidden/></td>
        <td><input type="checkbox" asp-for="@city.OnHeader" /></td>
        <td><input type="checkbox" asp-for="@city.OnProfile" /></td>
        <td><a asp-controller="Weather" asp-action="Delete" asp-route-cityId="@city.Id"><i class="fas fa-trash-alt color"></i></a></td>
        <td><button type="submit"><i class="fas fa-edit color"></i></button></td>
    </tr>
</form>
[HttpPost]
public IActionResult Update(WeatherModel theWeather, int cityId)
{
    _weatherService.Update(cityId, theWeather.OnHeader, theWeather.OnProfile);
    return RedirectToAction("Settings");
}

WeatherControllerUpdate API 期望接收 theWeathercityId 参数。预期接收数据如下:

{
  "theWeather": {
    "onHeader": `<boolean value>`,
    "onProfile": `<boolean value>`
  },
  "cityId": `<numeric value>`
}

当您提交 Update 的表单时,您正在向 API 发送数据,如下所示:

{
  "city": {
    "onHeader": `<boolean value>`,
    "onProfile": `<boolean value>`
  },
  "cityId": `<numeric value>`
}

因此,theWeather.onHeadertheWeather.onProfile 将获得默认的 boolean 值 (false),因为 theWeather 值未从前端接收。


解决方案

解决方案 1:为 <input> 元素应用 name 属性以实现模型绑定

  • 将包含 theWeather 对象的数据提交给 API。
<td><input type="checkbox" name="theWeather.OnHeader" asp-for="@city.OnHeader" /></td>
<td><input type="checkbox" name="theWeather.OnProfile" asp-for="@city.OnProfile" /></td>

方案二:重命名UpdatetheWeather参数为city

  • 确保 city 参数与 HTML 形式匹配。
public IActionResult Update(WeatherModel city, int cityId)
{
    _weatherService.Update(cityId, city.OnHeader, city.OnProfile);
    return RedirectToAction("Settings");
}

解决方案 3:使用 [Bind(Prefix = "city")] 属性

  • 模型绑定将在源中查找密钥 city 而不是 theWeather
public IActionResult Update(([Bind(Prefix = "city")] WeatherModel theWeather, int cityId)

参考资料

Custom Prefix - Model binding in ASP.NET Core

How to use Bind Prefix?