将 JavaScript 变量发送到 MVC 中的控制器

send a javascript variable to controller in mvc

本文关键字:MVC 控制器 JavaScript 变量      更新时间:2023-09-26

我必须向MVC中的控制器发送三态复选框状态。发布方法始终发送真/假。我想发送一个具有三种状态 (0,1,-1( 的 int 值。如何将三态值发送到控制器?

<script type="text/javascript">
    function ts(cb) {
        if (cb.readOnly) cb.checked=cb.readOnly=false;
        else if (!cb.checked) cb.readOnly = cb.indeterminate = true;
        return (cb.indeterminate ? -1 : cb.checked ? 1 : 0);
    }
</script>
@using (Html.BeginForm("Index", "Transitos", FormMethod.Get))
{
     <table class="table">
    <tr>
        <th>
            Sancionado: <input type="checkbox" id="Sancinado" name="Sancionado" onclick="ts(this)" />
        </th>
        <th>
            <input type="submit" value="Buscar" />
        </th>
    </tr>
</table>

}

在控制器中,我有:

public ActionResult Index(int? Sancionado )
{
        var Transitos = from s in db.Transitos
                       select s;
        if(Sancionado != null)
        {
            Transitos = Transitos.Where(x => x.Sancionado == (Sancionado==1 ? true : false));
        }
        return View(Transitos.ToList());
}
<script type="text/javascript">
    function ts(cb) {
        if (cb.readOnly) cb.checked=cb.readOnly=false;
        else if (!cb.checked) cb.readOnly = cb.indeterminate = true;
        var Sancionado = (cb.indeterminate ? -1 : cb.checked ? 1 : 0);
        $("#Sancinado").val(Sancionado); 
        $("form").submit(); //find your form and submit use more suit selector then just a "form"
    }
</script>