簡體   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