简体   繁体   中英

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

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.

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/

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