Programmatically Working with Checkboxes in MVC

Kmcnet 1,066 Reputation points
2024-12-05T22:51:46.3133333+00:00

Hello everyone and thanks for the help in advance. I am trying to understand how to set the value of a checkbox from a model in any other way then using some type of if logic. In other words, is there a way to set the value directly form the model. Any help would be appreciated.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-12-06T02:11:12.8033333+00:00

    Hi @Kmcnet

    In an ASP.NET Core MVC application, you can bind the checkbox to a model property by using Tag Helper.

    1.Model

    public class YourModel
    {
        public bool IsChecked { get; set; }
    }
    

    2.View

    @model YourModel
    <input type="checkbox" asp-for="IsChecked" />
    

    3.Controller

    public IActionResult Index()
    {
        var model = new YourModel { IsChecked = true }; // Set default value here if needed
        return View(model);
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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.

    Best regards,
    Rena


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.