How do I make a group of multi-select checkboxes in ASP.Net MVC with c# enum?

asp.net-mvc asp.net-mvc-5 c# entity-framework entity-framework-6

Question

I need to make a set of checkboxes where a user can select 1 or more markets. I would normally use a set of boolean values to accomplish this as it would be pretty strait forward and in my mind not take up much space in the database or take that long to load as they are only boolean values. It was suggested to me that I could use a single enum value in the database for the list of checkboxes. For example here is the enum

[Flags]
public enum Markets 
{

    Canada = 2,
    USA = 4,
    Iceland = 8,
    Brazil = 16,
    Italy = 32,
    Japan= 64,

}

Then in the database I could store 14 for Canada Usa and Iceland. I was wondering is enums the way to go in MVC for checkboxes and if so how would it work?

Note i'm using C# MVC4 and entity framework 5 but i'm about to transition to MVC5 entity framework 6.

Popular Answer

This is pretty straight forward in ASP.NET MVC, just make sure you have a list of inputs on your page with the same name and that you are binding to a list on the backend.

<form method="post" action="/Home/UpdateInts">
    <input type="checkbox" name="Markets" value="Canada" />
    <input type="checkbox" name="Markets" value="USA" />
    <input type="checkbox" name="Markets" value="Iceland" />
    <input type="checkbox" name="Markets" value="Brazil" />
    <input type="submit" />
</form>

That should do it. You could use the HtmlHelpers to create them or just use Razor Syntax.

Here is some more helpful info.

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why