Enum with mvc rendering in checkbox on my view, reaction of my controller?

戏子无情 提交于 2019-12-22 00:07:02

问题


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


来源:https://stackoverflow.com/questions/3305422/enum-with-mvc-rendering-in-checkbox-on-my-view-reaction-of-my-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!