Make a checkbox checked or unchecked based on the value?

前端 未结 8 1318
星月不相逢
星月不相逢 2020-12-29 23:02

How can we make a checkbox checked or unchecked programatically based on the value? That is to say, for a particular user if the value is true, the checkbox should be checke

8条回答
  •  悲哀的现实
    2020-12-29 23:38

    If you do not want to use @Html.CheckBoxFor for whatever reason and you'd like to stick to

              
    

    then this is what I found to be the best way to do it:

     
    

    The code that @Yasser provided above:

        checked="@(required ? "checked" : "")"
    

    Did not work for me because it was still adding the checked attribute to the element, and setting checked="" will still render the check box as checked, which was not the desired output, instead if you wrap the whole statement into a razor block like so:

         @(Convert.ToBoolean(Model.YourPropertyHere) == true ?   "checked='checked'" : string.Empty)
    

    you will get the desired results.

提交回复
热议问题