简体   繁体   中英

How do I keep the clicked state of a checkbox in asp.net

I'm really having problems with keeping the state of my checkbox in my mvc4 application. I'm trying to send its value down to my controller logic, and refresh a list in my model based on the given value, before I send the model back up to the view with the new values. Given that my checkbox is a "show disabled elements in list" type function, I need it to be able to switch on and off. I've seen so many different solutions to this, but I can't seem to get them to work :(

Here's a part of my view:

@model MyProject.Models.HomeViewModel

<div class="row-fluid">
    <div class="span12">
        <div class="k-block">
            <form action="~/Home/Index" name="refreshForm" method="POST">
                <p>Include disabled units: @Html.CheckBoxFor(m => m.Refresh)</p>
                <input type="submit" class="k-button" value="Refresh" />
           @* KendoUI Grid code *@
        </div>
    </div>

HomeViewModel:

public class HomeViewModel
{
    public List<UnitService.UnitType> UnitTypes { get; set; }
    public bool Refresh { get; set; }
}

The HomeViewController will need some refactoring, but that will be a new task

[HttpPost]
public ActionResult Index(FormCollection formCollection, HomeViewModel model)
{
    bool showDisabled = model.Refresh;

    FilteredList = new List<UnitType>();
    Model = new HomeViewModel();
    var client = new UnitServiceClient();
    var listOfUnitsFromService = client.GetListOfUnits(showDisabled);

    if (!showDisabled)
    {
        FilteredList = listOfUnitsFromService.Where(unit => !unit.Disabled).ToList();
        Model.UnitTypes = FilteredList;

        return View(Model);
    }

    FilteredList = listOfUnitsFromService.ToList();
    Model.UnitTypes = FilteredList;

    return View(Model);
}

You return your Model to your view, so your Model properties will be populated, but your checkbox value is not part of your model! The solution is to do away with the FormCollection entirely and add the checkbox to your view model:

public class HomeViewModel
{
    ... // HomeViewModel's current properties go here
    public bool Refresh { get; set; }
}

In your view:

@Html.CheckBoxFor(m => m.Refresh)

In your controller:

[HttpPost]
public ActionResult Index(HomeViewModel model)
{
    /* Some logic here about model.Refresh */
    return View(model);
}

As an aside, I can't see any reason why you'd want to add this value to the session as you do now (unless there's something that isn't evident in the code you've posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM