How do I set a checkbox in razor view?

后端 未结 10 2068
南笙
南笙 2020-12-05 17:01

I need to check a checkbox by default:

I tried all of these, nothing is checking my checkbox -

@Html.CheckBoxFor(m => m.AllowRating, new { @value          


        
相关标签:
10条回答
  • 2020-12-05 17:42
    <input type="checkbox" @( Model.Checked == true ? "checked" : "" ) />
    
    0 讨论(0)
  • 2020-12-05 17:42

    I did it using Razor , works for me

    Razor Code

    @Html.CheckBox("CashOnDelivery", CashOnDelivery) (This is a bit or bool value) Razor don't support nullable bool
    @Html.CheckBox("OnlinePayment", OnlinePayment)
    

    C# Code

     var CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
     var OnlinePayment = Convert.ToBoolean(Collection["OnlinePayment"].Contains("true") ? true : false);
    
    0 讨论(0)
  • 2020-12-05 17:46

    The syntax in your last line is correct.

     @Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
    

    That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.

    0 讨论(0)
  • 2020-12-05 17:47

    only option is to set the value in the controller, If your view is Create then in the controller action add the empty model, and set the value like,

    Public ActionResult Create()
    {
    UserRating ur = new UserRating();
    ur.AllowRating = true;
    return View(ur);
    } 
    
    0 讨论(0)
  • 2020-12-05 17:49

    You can do this with @Html.CheckBoxFor():

    @Html.CheckBoxFor(m => m.AllowRating, new{@checked=true });
    

    or you can also do this with a simple @Html.CheckBox():

    @Html.CheckBox("AllowRating", true) ;
    
    0 讨论(0)
  • 2020-12-05 17:54

    This works for me:

    <input id="AllowRating" type="checkbox" checked="@Model.AllowRating" 
    style="" onchange="" />
    

    If you really wants to use HTML Helpers:

    @Html.CheckBoxFor(m => m.AllowRating, new { @checked = Model.AllowRating})
    
    0 讨论(0)
提交回复
热议问题