CheckBox returns always false value

Maryan 21 Reputation points
2021-10-02T21:31:51.27+00:00

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");
    }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,246 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,041 Reputation points
    2021-10-03T15:30:19.493+00:00

    in the form the model is named "city" but on the action "theWeather". try:

         [HttpPost]
         public IActionResult Update(WeatherModel city, int cityId)
         {
             _weatherService.Update(cityId, city.OnHeader, city.OnProfile);
             return RedirectToAction("Settings");
         }
    
    0 comments No comments

  2. Yijing Sun-MSFT 7,061 Reputation points
    2021-10-04T05:41:00.193+00:00

    Hi @Maryan ,
    Yes,the first way you could to change the model name in the update method. Now, there are the second way that you could add bind prefix in the method. Just like this:

    public IActionResult Update([Bind(Prefix="city")]WeatherModel theWeather, int cityId)  
    

    When you used asp-for, it will generate id and name. The name is city.property. And you could bind the name.

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments