How to make ASP.Net MVC checkboxes keep state

Posted by myotherme on Stack Overflow See other posts from Stack Overflow or by myotherme
Published on 2010-04-29T07:14:50Z Indexed on 2010/04/29 7:17 UTC
Read the original article Hit count: 487

Filed under:
|

I have the following situation: I have a class Product that can have a confirmation from various Stations. So I have a ViewModel that holds the Product information, and a list of stations, and all the ProductStationConfirmations.

public class ProductViewModel
    {
        public Product Product { get; private set; }
        public List<Station> Stations { get; private set; }
        public Dictionary<string, ProductStationConfirmation> ProductStationConfirmations { get; private set; }

        public ProductViewModel(int productID)
        {
            // Loads everything from DB
        }

    }

In my partial view for inserting/editing I iterate over the stations to make a checkbox for each of them:

    <div class="editor-label">
        <%= Html.LabelFor(model => model.Product.Title)%>
    </div>
    <div class="editor-field">
        <%= Html.TextBoxFor(model => model.Product.Title)%>
        <%= Html.ValidationMessageFor(model => model.Product.Title)%>
    </div>
    <fieldset>
        <legend>Station Confirmations</legend>
        <% foreach (var station in Model.Stations)
     {  %>
        <div class="nexttoeachother">
            <div>
                <%= Html.Encode(station.Name) %>
            </div>
            <div>
                <%= 
        Html.CheckBox("confirm_"+station.ID.ToString(),
        Request["confirm_"+station.ID.ToString()] == null ? 
                    Model.ProductStationConfirmations.ContainsKey(Entities.ProductStationConfirmation.MakeHash(Model.Product.ID, station.ID))
            : Request["confirm_" + station.ID.ToString()].Contains("true")

        ) 
        %>
            </div>
        </div>
        <% } %>
    </fieldset>

This works and I can process the Request values to store the confirmed Stations, but it is really messy. I made it this way to preserve the state of the checkboxes between round trips if there is a problem with the model (missing title, bad value for decimal, or something that can only be checked server-side like duplicate tile). I would expect that there is a nicer way to do this, I just don't know what it is.

I suspect that I need to change the shape of my ViewModel to better accommodate the data, but i don't know how. I am using MVC 2.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about check