Home > Software engineering >  ASP.NET CheckBox returns always false value
ASP.NET CheckBox returns always false value

Time:10-04

Does anyone know why I'm getting always a false value when I update the form? I tried with (value="false") into the checkbox but still doesn't work. Any help is appreciated!

<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");
}

CodePudding user response:

WeatherController's Update API expects that will receive theWeather and cityId parameters. The expected receive data is as below:

{
  "theWeather": {
    "onHeader": `<boolean value>`,
    "onProfile": `<boolean value>`
  },
  "cityId": `<numeric value>`
}

While you submit the form for Update, you are sending data to API as below:

{
  "city": {
    "onHeader": `<boolean value>`,
    "onProfile": `<boolean value>`
  },
  "cityId": `<numeric value>`
}

Hence, theWeather.onHeader and theWeather.onProfile will get the default boolean value (false) as theWeather value is not received from front-end.


Solutions

Solution 1: Apply name attribute for <input> elements aimed for model binding

  • Will submit the form with data includes theWeather object to 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>

Solution 2: Rename Update theWeather parameter to city

  • Ensure that the city parameter is matched with the HTML form.
public IActionResult Update(WeatherModel city, int cityId)
{
    _weatherService.Update(cityId, city.OnHeader, city.OnProfile);
    return RedirectToAction("Settings");
}

Solution 3: Use [Bind(Prefix = "city")] attribute

  • Model binding will looking through the sources for the key city instead of theWeather.
public IActionResult Update(([Bind(Prefix = "city")] WeatherModel theWeather, int cityId)

References

Custom Prefix - Model binding in ASP.NET Core

How to use Bind Prefix?

  • Related