MikeTWebb
MikeTWebb

Reputation: 9279

MVC3 Drop Down or ListBox with dynamic check boxes

I have an MVC3 C#.Net web app. I have a requirement to display a list of check boxes (either in a drop down or a List Box) dynamically based on a table in our db. The table can contain 1:500 entries. I then need to pass the selected check boxes to the Controller in order to perform an action on each selection. Any ideas on an implementation?

Upvotes: 0

Views: 2933

Answers (2)

Kevin
Kevin

Reputation: 127

the answer provided by Jay accomplishes exactly what you need. If you want to put the items in a list you can do it by surrounding the markup with a div control lie below

<div style="height:40px;overflow:auto;">
    <%  foreach (var item in Model) { %> 
            <input type="checkbox" id="chxBx<%=item.Key%>" name="chxBxGroupName" value="<%=item.Key% >"/> 
            <label for="chxBx<%=item.Key%>"><%=item.Value%></label> 
            <br/><br/> 
    <%  } %>   
</div>

unfortunately you cant have checkboxes in a <select />, but if you really wanted it to look like a select list you could add some JQuery that processes onclick of a textbox and shows the div. This obviously would require some jQuery and might not be worth it

Upvotes: 0

Timeout
Timeout

Reputation: 7909

There are many ways to go about this but here is a general demo.

You can pass a list of the checkbox values and descriptions either on the Model (as this example does), ViewData[""] dictionary or ViewBag (MVC3+).

Then in your view loop through them and add them to your form using the name="chxBxGroupName" to group them.

Now create a controller action to post to that takes a List of the value type (in this example int) with the parameter naming matching the name="chxBxGroupName".

It will post a list of checked values.

The post page will just print out:

123
456

// This is your landing page. It gathers the data to display to the user as checkboxes.
public ViewResult MyPageWithTheCheckboxes()
{
    // For example: Assume a Dictionary with the checkbox value and description
    // Replace with DB call, etc.
    return View(new Dictionary<int, string> { { 123, "Foo" }, { 456, "Bar" } });
}

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Dictionary<int,string>>" %>

<!-- Rest of HTML page... -->

<form id="frm1" action="<%=Url.Action("MyPost")%>" method="post">
<%  foreach (var item in Model) { %>
        <input type="checkbox" id="chxBx<%=item.Key%>" name="chxBxGroupName" value="<%=item.Key%>"/>
        <label for="chxBx<%=item.Key%>"><%=item.Value%></label>
        <br/><br/>
<%  } %>    
    <input type="submit" value="Go!"/>
</form>

<!-- Rest of HTML page... -->

public ContentResult MyPost(List<int> chxBxGroupName)
{
    return Content(string.Join(Environment.NewLine, chxBxGroupName ?? new List<int>()), "text/plain");
}

Upvotes: 1

Related Questions