checkbox is checked only after submission

You can store the checkedTypes in a ViewBag, then determine, then determine whether the checkbox needs to be selected on the front end.

A simple example as below:

View:

@{ 
    var types = new List<MyType>
    {
        new MyType{Id = 1, Name ="AA"},
        new MyType{Id = 2, Name ="BB"},
        new MyType{Id = 3, Name ="CC"},
    };
    var checkedTypes = ViewBag.checkedTypes;
}

<form method="post">
    @foreach (var type in types)
    {
        if (checkedTypes != null && checkedTypes.Contains(type.Id))
        {
            <input type="checkbox" name="checkedTypes" value="@type.Id" checked />
        }
        else
        {
            <input type="checkbox" name="checkedTypes" value="@type.Id" />
        }

        <label>@type.Name</label>
    }
    <button type="submit" class="btn customGreen">Set filters</button>
</form>

Controller:

public IActionResult Index()
{
    return View();
}

[HttpPost]
public async Task<ViewResult> Index(List<int> checkedTypes)
{
    if (checkedTypes.Count != 0)
    {
        ViewBag.checkedTypes = checkedTypes;
    }
    return View();
}

Result:

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top