How to set a CheckBox by default Checked in ASP.Net MVC

后端 未结 7 1388
北荒
北荒 2020-11-28 11:36

I am using CheckBox in my ASP.Net MVC project,

i want to set checkBox by default checked,

My CheckBox is

@Html.CheckBoxFor(model => model.         


        
相关标签:
7条回答
  • 2020-11-28 12:14

    You could set your property in the model's constructor

    public YourModel()
    {
        As = true;
    }
    
    0 讨论(0)
  • 2020-11-28 12:15

    An alternative solution is using jQuery:

        <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                PrepareCheckbox();
            });
            function PrepareCheckbox(){
                document.getElementById("checkbox").checked = true;
            }
        </script>
    
    0 讨论(0)
  • 2020-11-28 12:17
    @Html.CheckBox("yourId", true, new { value = Model.Ischecked })
    

    This will certainly work

    0 讨论(0)
  • 2020-11-28 12:19

    My way is @Html.CheckBoxFor(model => model.As, new { @value= "true" }) (meaning is checked)

    0 讨论(0)
  • 2020-11-28 12:21

    Old question, but another "pure razor" answer would be:

    @Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
    
    0 讨论(0)
  • In your controller action rendering the view you could set the As property of your model to true:

    model.As = true;
    return View(model);
    

    and in your view simply:

    @Html.CheckBoxFor(model => model.As);
    

    Now since the As property of the model is set to true, the CheckBoxFor helper will generate a checked checkbox.

    0 讨论(0)
提交回复
热议问题