繁体   English   中英

ASP.NET Core CheckBox 总是返回假值

[英]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:为目标 model 绑定的<input>元素应用name属性

  • 将提交带有数据的表格包括theWeather object 到 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>

解决方案 2:将Update theWeather参数重命名为city

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

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

  • Model 绑定将查找关键city的来源而不是theWeather
public IActionResult Update(([Bind(Prefix = "city")] WeatherModel theWeather, int cityId)

参考

自定义前缀 - Model 绑定在 ASP.NET Core

如何使用绑定前缀?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM