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 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This solutions is working fine, but there is no way to support natively this features ???
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.