有誰知道為什么我在更新表單時總是得到一個錯誤的值?我嘗試將 (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");
}
uj5u.com熱心網友回復:
WeatherController的UpdateAPI 預計將接收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:name為<input>用于模型系結的元素應用屬性
- 將包含資料的表單提交
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>
解決方案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)
參考
自定義前綴 - ASP.NET Core 中的模型系結
如何使用系結前綴?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/313033.html
標籤:asp.net asp.net核心 asp.net-mvc-3
上一篇:按價值型別對物件進行排序
