views:

67

answers:

1

If i got a list of checkbox in a View, and this list came from Enum (flags). If my checkbox as all the same name, did my controller will update automaticly my Enum (flags) values in my ViewModel with multiple selection ?

Suppose i get in my View

<% foreach (var t in Enum.GetValues(typeof(FoodType)))
           {
               Response.Write(t.ToString() + " ");
            %>
            <input type="checkbox" name="TypeOfFood"  value="<%:(int)t %>" />

            <% }%>

My Controller working like this

public ActionResult Manage(FoodEntity food)
        {


        }

If i check many check box when i look then FoodType property in my foodEntity, only the value of the first checkbox is selected, but my enum is a flag... what i need, if i want support flag ?

thanks.

+1  A: 

Unfortunately no.

It will just grab the first checked value and assign that to your value field.

That would be a pretty cool feature though.

Heres a quick way to get the value you're looking for back into your model:

int newEnumValue = Request.Form["CheckBoxField"].Split(',').Aggregate(0, (acc, v) => acc |= Convert.ToInt32(v), acc => acc);
jwsample
This solutions is working fine, but there is no way to support natively this features ???
Cédric Boivin
You could override the defaultmodelbinder, check that the target type is an enum, inspect it for the flags attribute, and OR the values together.... but depending on how much you need to do it it might be overkill.
jwsample