zlatan114r
zlatan114r

Reputation: 37

Checkbox staying checked after submit

So I have these checkboxes that passes values to the controller, and these values are then used to get something back from the database. But when I click the submit button everything works, but the checked checkboxes are now unchecked. This is the view:

<form>
@foreach(var type in types) {
<input type="checkbox" name="checkedTypes" value="@type.id" />
<label>@type.Name</label>
}
<button type="submit" class="btn customGreen">Set filters</button>
</form>

And this is the controller:

public async Task < ViewResult > Index(List < int > checkedTypes) 
{
var products = from p in _db.Products
select p;

if (checkedTypes.Count != 0) {
products = products.Where(p =>checkedTypes.Contains(p.TypeId));
}

return View(product);
}

Is there a way to keep checked checkboxes stay checked after submit? Or is there a better way to handle checkboxes with .net core.

Upvotes: 1

Views: 876

Answers (1)

mj1313
mj1313

Reputation: 8469

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

Upvotes: 2

Related Questions