Robin-Hoodie
Robin-Hoodie

Reputation: 4974

Making a checkbox without a boolean in mvc 4?

So I have the following enum :

public enum Type
{
A ,
S
}

At the moment I have the following code in my view which uses this enum:

<div class="editor-label">
@Html.Label("Type")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Type, new SelectList(Enum.GetValues(typeof(Project.Domain.POCO.Type))))
@Html.ValidationMessageFor(model => model.Type)
</div>

However, the original idea was to use a checkbox and not a dropdownlist, this was just a temporarily solution. Whenever I try using @Html.CheckBoxFor it expects a boolean type, is there any way to work around this and keep using my enumtype instead of creating a boolean (since the enum is used in multiple classes and I'd have to make a lot of changes if I were to change it into a boolean)

Upvotes: 0

Views: 261

Answers (1)

middelpat
middelpat

Reputation: 2585

You can parse your enum to a boolean since your enum types are also int values:

A = 0, S = 1..

since you only have two values you always have 0 or 1. This can be parsed into a bool. Note that this is a very dirty solution.

when you use:

Boolean.Parse((int)model.Type)

you'll get a bool. A = false, S = true

However I wouldn't recommend using this approach

Upvotes: 3

Related Questions