简体   繁体   中英

checkbox values true or false alternative to string in cshtml

Is there an alternative and more "correct" method to turn the value of a checkbox into a bool.

My cshtml code:

@{
    Page.Title = "";
    Layout = "~/_Layout.cshtml";

    bool checked = false;

    if(isPost)
    {
        if(Request["chkbx"] == "on")
        {
            checked = true;
        }
    }
}

<div>
    <input type="checkbox" name="chkbx" />
</div>

In ASP.NET MVC Razor views in general aren't supposed to mess with things like Request .

It's up to the Controller to create a ViewModel object from the Request (using ModelBinding preferably) then passing the created object to the View .

Yet, if you're reluctant on changing course to the ViewModel path:

You can use built in HTML Helpers for Razor: @Html.CheckBox("chkbx", checked)

Alternatively, if you prefer to code your HTML elements manually, this might look cleaner: <input type="checkbox" name="chkbx" @(checked ? "checked" : "") />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM