Search code examples
asp.net-mvchtml-helpercheckboxfor

Html CheckBoxFor helper in MVC 4 Razor - Cannot implicitly convert type 'int' to 'bool'


I am trying to render list of checkboxes from an external db table BUT I keep getting this error: Cannot implicitely convert type 'int' to 'bool'.

I am guessing its not happy b/c of my strongly type view which returns a list. Can anyone please help. Thank you in advance.

my model

public partial class tblCity
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int IsSelected { get; set; }
} 

my view

@model List<Demo.Models.Sample>    

@for (int i = 0; i < Model.Count; i++)
{    
   @Html.CheckBoxFor(m => m[i].ID)  **Cannot implicitly convert type 'int' to 'bool'**
}

Solution

  • This is because you are giving it an int

    @for (int i = 0; i < Model.Count; i++)
    {    
       @Html.CheckBoxFor(m => m[i].ID) <- ID is an Int
    }
    

    You'd need to give it a bool. Maybe IsSelected was supposed to be a bool, and that was what you were looking for?

    public partial class tblCity
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    } 
    

    Then the view

    @model List<Demo.Models.Sample>    
    
    @for (int i = 0; i < Model.Count; i++)
    {    
       @Html.CheckBoxFor(m => m[i].IsSelected )
    }