vendredi 7 août 2015

How to create checkboxes for enum type in MVC5?

I'm using ASP.NET MVC5, and I have an enum type defined like the one below:

public enum Type
{
    Classic,
    Vintage,
    Modern,
    Futuristic
}

What I want to do is create checkbox for every option in the enum, and make the user able to select zero or more of the checkboxes. Then, I want to save the checked options into the database.

In my model, I have something like this:

public class Ad
{
    public int Id { get; set; }

    [Required]
    public Type[] Type { get; set; }

    public DateTime PublishedOn { get; set; }

    // Rest removed for brevity
}

Afterwards, in my view I tried something like this:

<div class="form-group">
    @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @for (int i = 0; i < Model.Type.Count(); i++)
        {
            @Html.CheckBoxFor(model => model.Type[i])
        }

        @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
    </div>
</div>

Though, when I try to render the view, I get an error message saying:

Compiler Error Message: CS0029: Cannot implicitly convert type 'MyApp.Data.Type' to 'bool'

Any idea how to solve this problem? I would also like to see how can I pass the values to the controller and save into the database.




Aucun commentaire:

Enregistrer un commentaire