-1

I want to create a checkbox using enum. I can create a simple checklist using enum without any issues, but it give me error for when I use asp-for="" in my checklist.

Whenever I use asp-for="", I get this error:

InvalidOperationException: Unexpected 'asp-for' expression result type 'Website.Data.Enum.CollectionCategory' for . 'asp-for' must be of type 'System.Boolean' or 'System.String' that can be parsed as a 'System.Boolean' if 'type' is 'checkbox'.

I have created radio buttons using enum with asp-for="" and it worked without any problem.

I searched online why that is the case and here is what I found:

Unfortunately, to Render Checkbox for each enum value is not possible – by definition you always only select one value of an enumeration. If you want checkboxes, you can make separate Boolean attributes for each checkbox.

I have searched for multiple solutions but unfortunately, my problem is still unresolved.

Here is my code:

Enum definition:

public enum CollectionCategory
{
    [Display(Name = "Veg")]
    Veg = 0,

    [Display(Name = "NonVeg")]
    NonVeg = 1,

    [Display(Name = "Breakfast")]
    Breakfast = 2,

    [Display(Name = "Lunch")]
    Lunch = 3,

    [Display(Name = "Dinner")]
    Dinner = 4
}

Model class:

public class Post
{
    // Code Before

    public CollectionCategory CollectionCategory { get; set; }

    // Code After
}

View model:

public class CreatePostViewModel
{
    // Code Before
    public CollectionCategory CollectionCategory { get; set; }
}

Controller:

public IActionResult Create()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
    if (ModelState.IsValid)
    {
        var post = new Post
        {
            // Code before
            CollectionCategory = postVM.CollectionCategory,                    
        };

        _postInterface.Add(post);
        return RedirectToAction("Index");
    }
    else
    {
        // Error
    }

    return View(postVM);
}

View (works fine without asp-for=""):

<div class="col-md-12 mb-3">
    @foreach (var value in Enum.GetValues(typeof(CollectionCategory)))
    {
        <input type="checkbox" asp-for="CollectionCategory" class="btn-check" id="@value" value="@((int)value)" required>
        <label asp-for="CollectionCategory" class="btn btn-outline-primary" for="@value">@value</label>
    }
</div>

Thank you for your help.

1

1 Answer 1

2

Firstly,juding from your codes in your controller,you just want a single CollectionCategory in your viewmodel,radio buttons is more suitable for your sceanaior

If you want bind value to multipule CollectionCategory,you have to create a model that has a property type of bool for checkbox , and create a hiden input to hold the value of the enum;

a similar issue I once answered here.

Here's a minimal example for you,hopes help:

Models:

public enum CollectionCategory
{
    [Display(Name = "Veg")]
    Veg = 0,

    [Display(Name = "NonVeg")]
    NonVeg = 1,

    [Display(Name = "Breakfast")]
    Breakfast = 2,

    [Display(Name = "Lunch")]
    Lunch = 3,

    [Display(Name = "Dinner")]
    Dinner = 4
}


public class CheckboxModel
{
    public bool IsChecked { get; set; }
    public CollectionCategory CollectionCategory { get; set; }

    public string Label { get; set; }
}


public class CreatePostViewModel
{
    public List<CheckboxModel> Checks { get; set; } = new();
}

Controller:

public IActionResult Check()
{
    var viewmodel = new CreatePostViewModel();
    foreach (var name in Enum.GetNames(typeof(CollectionCategory)))
    {
        var checkboxmodel = new CheckboxModel()
        {
            CollectionCategory = ( CollectionCategory)Enum.Parse(typeof(CollectionCategory), name,true),
            IsChecked = false,
            Label = name,

        };
        viewmodel.Checks.Add(checkboxmodel);
    }

    return View(viewmodel);
}
[HttpPost]
public IActionResult Check(CreatePostViewModel viewmodel)
{
    //...........
    return View(viewmodel);
}

View:

@model CreatePostViewModel

<form method="post">

    @for (int i = 0; i < Model.Checks.Count; i++)
    {
        <div class="col-md-12 mb-3">
            <input type="checkbox" asp-for="@Model.Checks[i].IsChecked"   >
            <label asp-for="@Model.Checks[i].Label">@Model.Checks[i].Label </label>
            <input type="text" asp-for="@Model.Checks[i].CollectionCategory" hidden />
            <input type="text" asp-for="@Model.Checks[i].Label" hidden />
        </div>
     }
    
    <input type="submit" value="submit"/>
</form>

Result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.