简体   繁体   中英

How can I bind custom enum values to a @Html.CheckBox

I have enum of 3 values. I want to bind the enum values to a @Html.CheckBox except the first one. How this can be acheived?

My enum -

public enum EType
{
    [EnumMember]
    UNKNOWN = 0,
    [EnumMember]
    Value1 = 1,
    [EnumMember]
    Value2 = 2
}

This is my ViewBag in controller which contains the enum values-

ViewBag.Enums = from Enum e in Enum.GetValues(typeof(EType))
                select new SelectListItem { Value = Convert.ToInt32(e).ToString(), Text =((EType)e).ToString() };

This is my Html-

<td>
@{
IEnumerable<SelectListItem> Enums = ViewBag.Enums;
foreach (var item in Enums)
 {                                                                   
  @Html.CheckBox(item.Text, false, new { item.Value }) 
  <label>@item.Text</label><br />
 }
}

In View, try this

var enumList = Enum.GetValues(typeof(EType)).Cast<EType>().Skip(1);

@foreach (var optVal in enumList)
{ 
<label>
    @Html.CheckBox(optVal.ToString(), false, new { value = Convert.ToInt32(optVal).ToString()})
    @optVal

</label>
}

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