[英]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.