gpt4 book ai didi

HTML.Checkboxfor 到切换按钮 HTML?

转载 作者:太空狗 更新时间:2023-10-29 14:46:40 26 4
gpt4 key购买 nike

有没有办法将@HTML.Checkboxfor 转换为切换 html 按钮?我引用了 https://www.w3schools.com/howto/howto_css_switch.asp 中的切换按钮样式

目前它的工作方式是:

@Html.CheckBoxFor(model => model.IsEnabled, new { @checked = "checked", @Name = "DelegateChkBox" })

更改为:

    <td class="slider-td">
<label class="switch">
<input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true" data-val-required="The IsEnabled field is required." data-val="true" data-bind="checked: IsEnabled">
<div class="slider round"></div>
</label>
</td>

切换按钮只有在选中时才有效并回发到 Controller : enter image description here

否则默认情况下它不会回发到 Controller UNCHECKED :

enter image description here

任何帮助将不胜感激!谢谢!

最佳答案

根据一些实验和发现,我发现您需要包含由助手 ( Html.CheckBoxFor ) 生成的隐藏字段,如下面的样式所示:

<style type="text/css">
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

.switch input {display:none;}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
}

/* include generated hidden field here */
input[type="checkbox"]:checked + input[type="hidden"] + .slider,
input[type="checkbox"]:checked + .slider {
background-color: #2196F3;
}

/* include generated hidden field here */
input[type="checkbox"]:focus + input[type="hidden"] + .slider,
input[type="checkbox"]:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}

/* include generated hidden field here */
input[type="checkbox"]:checked + input[type="hidden"] + .slider:before,
input[type="checkbox"]:checked + .slider:before {
transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
border-radius: 34px;
}

.slider.round:before {
border-radius: 50%;
}
</style>

查看用法示例(只需将 <input type="checkbox" /> 更改为 @Html.CheckBoxFor ):

<label class="switch">
@Html.CheckBoxFor(model => model.IsEnabled)
<div class="slider round">
</div>
</label>

要确保在执行回发之前在客户端检查复选框,您可以使用下面的 jQuery 代码:

// change event may modified to other events
$("#IsEnabled").change(function () {

// check if checkbox is being checked
// taken from /a/23007488 by Alexandru Chichinete
if ($("#IsEnabled").is(":checked"))
{
// enable form submit
}
});

演示示例:.NET Fiddle

引用资料:

Styling checkboxes in MVC 4

How can I apply a CSS style to Html.CheckBoxFor in MVC 5

@Html.checkboxfor - Get checkbox value using id

关于HTML.Checkboxfor 到切换按钮 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42966789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com