2

In my view I have,

@Html.CheckBoxFor(m => m.IsExist, new { @id = "IsExist" })

In my Model I have IsExist value from DB. Either true or false.

Now how can I 'Check' or 'Uncheck' the option, based on the true or false value in IsExist. I expected, on binding by default the check box takes the value of Model. Howeverr that is not happening.

How can i achieve it?

tereško
  • 58,060
  • 25
  • 98
  • 150
TBA
  • 1,077
  • 5
  • 41
  • 80

3 Answers3

3

Here how i achieved it

@Html.CheckBox("VC",(item.isVC=="Y") ? true : false)

where my item.isVC has value "Y" or "N"

Phani Kumar M
  • 4,564
  • 1
  • 14
  • 26
3

Below snippet indicates an alternate way of having checkbox created and conditionally making it checked/unchecked. The following approach is also useful to get the value of checkbox by traditional approach using jquery.

@model myproject.Models.StudentModel


<div class="row">
   <label class="checkbox-inline">
     <input type="checkbox" name="selfStudy" checked="@Model.IsExist"><b>Self Study</b>
   </label>
</div>
Sreekanth
  • 385
  • 1
  • 6
  • 17
  • @RikinPatel, It would be great if you could try it first and then give your insights on it. – Sreekanth May 11 '20 at 12:43
  • @Sheekanth I have added comment so may be there is some reason right? Check it here. https://jsfiddle.net/patelriki13/y5vhko9z/1/ – Rikin Patel May 12 '20 at 03:56
  • 1
    @RikinPatel, My answer is using MVC model to set **checked** attribute but your fiddle is using text true/false being set in html directly, it won't work in that way. Please check my approach [here](https://dotnetfiddle.net/a9cZne). – Sreekanth May 12 '20 at 09:30
2

You can do this to check a checkbox :

if (Model.IsExist) {
    @Html.CheckBoxFor(m => m.IsExist, new { @id = "IsExist", "checked" = "checked"}) 
} 

Hope it's help

Joffrey Kern
  • 6,449
  • 3
  • 25
  • 25
  • Thanks actually I was manually initializing those checkboxes in a Jquery. There I set it to null. Once I removed as per false or true the code will work. – TBA Jul 09 '13 at 13:34