Enum with mvc rendering in checkbox on my view, re

2019-04-15 06:08发布

问题:

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:

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);