asp.net-corerazorcheckbox

Asp.NET Core Model Binding input type checkbox not remains unchecked


I am facing some strange issue, I am using Asp.net Core.

I have Model class which I am binding to my razor view and here is the model implementation.

        {
            PatientDetailReport = new ReportModel();
            itemid = true;
        }
public ReportModel PatientDetailReport { get; set; }
        public bool itemid { get; set; }

Report Model Class has few bool properties like public bool IdentityNumberDisplay { get; set; }

I am trying to bind model in both of these ways as mentioned by mostly blogs and also on stackoverflow

      (1) <input type="checkbox"  asp-for="@Model.PatientDetailReport.IdentityNumberDisplay"   />
     (2)  @Html.CheckBoxFor(m=>m.PatientDetailReport.IdentityNumberDisplay,new { })
    </td>

but both of these cases remains unchecked.

for first case, I also tried with value=@Model.PatientDetailReport.IdentityNumberDisplay but at jquery level I have to check it with value =True or False (as string) I am able to modify the checkbox, but the value is not posting on Controller.

Please can anyone guide me regarding to this case. Why the case 2 is not working,however most of the blogs are saying to use like that?

Thanks


Solution

  • I resolved this issue using JQuery by checking Checkbox value from Model which is coming as 'True' in string format, and then assigned checked property to true.

     @Html.CheckBoxFor(m=>m.PatientDetailReport.IdentityNumberDisplay
       ,new {value=Model.PatientDetailReport.IdentityNumberDisplay })
    
     $.each($("input[type='checkbox']"), function (e) {
                    console.log($(this).val());
                    //debugger;
                    if ($(this).val() === 'True') {
                        $(this).prop('checked', true);
                    }
    
                })
    

    I am not sure it is correct or not but this resolved my issue for asp.net core model's bool property for checkbox or radio button.