[英]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");
}
WeatherController
的Update
API 预计将收到theWeather
和cityId
参数。 预期接收数据如下:
{
"theWeather": {
"onHeader": `<boolean value>`,
"onProfile": `<boolean value>`
},
"cityId": `<numeric value>`
}
当您提交Update
表单时,您正在向 API 发送数据,如下所示:
{
"city": {
"onHeader": `<boolean value>`,
"onProfile": `<boolean value>`
},
"cityId": `<numeric value>`
}
因此, theWeather.onHeader
和theWeather.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")]
属性
city
的来源而不是theWeather
。public IActionResult Update(([Bind(Prefix = "city")] WeatherModel theWeather, int cityId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.