Chris McKee
Chris McKee

Reputation: 4387

Checkboxes in ASP.net MVC (c#)

I'm creating a checkbox list to handle some preferences as follows...

        <ul>
            <%foreach (var item in ViewData["preferences"] as IEnumerable<MvcA.webservice.SearchablePreference>)
              {
                  var feature = new StringBuilder();
                  feature.Append("<li>");
                  feature.Append("<label><input id=\"" + item.ElementId + "\" name=\"fpreferences\" type=\"checkbox\" />" + item.ElementDesc + "</label>");
                  feature.Append("</li>");
                  Response.Write(feature);
              }
            %>
        </ul>

The data handed to the viewdata of SearchablePreference[] and the list displays fine.

The question is; How would I repopulate the selected boxes if the page had to return itself back (i.e failed validation).

In webforms its handled automatically by the viewstate; with the other input elements I'm simply passing the sent-data back to the page via ViewData.

Thanks

Upvotes: 0

Views: 1414

Answers (4)

Martin
Martin

Reputation: 11041

You have way too much code in the View. This should be done in the controller. The View should be:

    <ul>
        <%foreach (var item in ViewData["preferences"] as IEnumerable<MvcA.webservice.SearchablePreference>)
          {
              <li>
                  <%=Html.Checkbox(........) %>
              </li>
          }
        %>
    </ul>

Upvotes: 0

AndreasKnudsen
AndreasKnudsen

Reputation: 3481

I agree with RichardOD, use Html.Checkbox

but if you insist on doing it manually, here´s how

Use an object to hold the data (whether something is selected or not) and give that to the view, when populating the checkboxes, check if the relevant value is set and if so set html "checked=\"checked\"" on the checkbox

The first time you render this, the object will have only false datas, so nothing will be selected.

Upvotes: 0

Russell Steen
Russell Steen

Reputation: 6612

You have to read off all of the values, then add them to the ViewData of the view you come back to, writing them into the checkboxes in the view display (preferably with Html.Checkbox). To my knowledge, Html.Checkbox does not automatically manage viewstate for you.

Assuming i have a standard CRUD object I very often have something like this in the Edit view. (I use the same view for edit and new)

<input (other input attribute here) value="<%=(myObj == null ? "" : myObj.AppropriateProperty)%>" />

Upvotes: 0

RichardOD
RichardOD

Reputation: 29157

Use Html.Checkbox instead.

Upvotes: 2

Related Questions