【问题标题】:ASP.Net MVC6 Checkbox value to controllerASP.Net MVC6 复选框值到控制器
【发布时间】:2017-12-14 09:35:36
【问题描述】:

我正在尝试自己创建一个复选框,当它被点击时,它将根据结果将真或假值发送回控制器,它将添加或删除它并基于此返回结果。我没有使用模型,我希望在单击提交请求后没有按钮。

到目前为止,我有:

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   <label>View All Tickets @Html.CheckBox("chkAllTickets")</label>
}

我只想发回类似的东西 public ActionResult Index(bool Checked) 和checked 在点击时将保持真或假。

我需要使用 jQuery 还是它更简单,我只是错过了一些东西。到目前为止,我已经轻松完成了所有事情,这给我带来了很多麻烦。

提前致谢。

【问题讨论】:

  • 你的模型中有这个属性吗?
  • 这是一个类似的问题,但我也想在单击 chekcbox 时提交。不,我宁愿在我的模型中没有它,但我在控制器的一个类中将它作为 public bool ChkAllTickets { get;放; }
  • 现在您正在使用一个表单,这意味着表单需要提交(通常是单击“提交”按钮的结果)才能联系服务器。从您的描述看来,您希望它在他们单击复选框时立即发生,这意味着 ajax 调用会更合适。

标签: c# asp.net-mvc checkbox


【解决方案1】:

嗨 Adam,如果我正确理解了您的问题,这很简单,也就是说,您可以在控制器操作方法中使用复选框的名称,并根据选中或未选中来获取真或假。

例如:

 @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
       <label>View All Tickets @Html.CheckBox("chkAllTickets")</label>
    }

在控制器中:

Public class HomeController:Controller
{
   public actionresult Index(bool chkAllTickets)
    {
            //other logic
    }

}

注意:根据绑定到复选框的值,在 action 方法中指定您的数据类型。

【讨论】:

    【解决方案2】:

    我解决了复选框的问题。

    <div style="display:inline-block">
        <label style="margin-left:10px;">
            <span><label>View All Tickets @Html.CheckBox("chkAllTickets")</label></span>
        </label>
    </div>
    

    我使用 javascript 和 jquery 来解决这个问题。 如果对 1 个动作为真,则对另一个动作为假。

    $(document).ready(function () {
            $('#chkAllTickets').on('change', function () {
                var theUrl = '';
                this.value = this.checked ? 1 : 0;
                if (this.value == 1)
                {
                    theUrl = '@Html.Raw(Url.Action("Index", "Home", new { SortField = ViewBag.SortingPagingInfo.SortField, SortDirection = ViewBag.SortingPagingInfo.SortDirection, ChkAllTickets = true }))';
                    window.location = theUrl;
                }
                else
                {
                    theUrl =  '@Html.Raw(Url.Action("Index", "Home", new { SortField = ViewBag.SortingPagingInfo.SortField, SortDirection = ViewBag.SortingPagingInfo.SortDirection, ChkAllTickets = false }))';
                    window.location = theUrl;
                }
    
            });
        });
    

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多