使用if else

时间:2016-09-30 06:43:29

标签: javascript jquery twitter-bootstrap asp.net-mvc-5

我正在使用asp.net MVC 5.我已经放置了一个带input type checkbox的引导切换开关按钮

Bellow是我的切换开关的图像

enter image description here

从我的查询中我得到一个命令名称cmd_Name,其中有开启关闭值并且基于此值我只想要从开 - 关或从开 - 关

更改切换开关

Bellow是我用于切换的剃刀语法

@using (Html.BeginForm())
{
//var cmd_Name = Session["cmd_Name"];
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset style="height:60px">
    <legend style="text-align:center;  font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
    <input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">

</fieldset>}

Bellow是我的切换脚本

<script type="text/javascript">
var search = '@Session["search"]';
var cmd_Name = '@Session["cmd_Name"]';
var data = {}
//alert(cmd_Name);
$(window).on('load', function () {

    // here cmd_Name i having On or Off value 

    // i want to put a check like bellow

    if(cmd_Name == "On")
    {
      // then the toggle switch (checkbox) moves to On
     // what should place here that moves the switch from on to off and vise versa
    }
    else
    {
      //then toggle switch (checkbox) moves to Off
    }

})</script>

更新代码

Bellow是我更新的代码和错误的图片

enter image description here

更新了代码2

我在布局<{p>>的head部分中有以下声明

<head>
<title>@ViewBag.Title</title>
@*All the javascript and css files that are required by the
    application can be referenced here so that there is no
    need to refrence them in each and every view*@


<script type="text/javascript" src="~/Scripts/jquery-3.1.0.min.js"></script>
<script src="~/Scripts/bootstrap-toggle.js"></script>
<link href="~/Content/bootstrap-toggle.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />    
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?key=MyKey"></script>


<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="icon" href="favicon.ico" type="image/ico" />
<link rel="shortcut icon" href="~/favicon.ico" /></head>

请参阅bundle.config

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

我在if...else $("#test_id").checked = true/false中尝试了很多内容,我也试过document.getElementById("test_id").checked

但是一切都是徒劳的,任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:0)

试试这个 -

if(cmd_Name == "On") {
    $("#test_id").attr("checked", "checked");
} else if(cmd_Name == "Off") {
   $("#test_id").removeAttr("checked");
}

你也可以这样做

if(cmd_Name == "On") {
    $("#test_id").bootstrapToggle("on")
} else if(cmd_Name == "Off") {
   $("#test_id").bootstrapToggle("off")
}