【问题标题】:Passing values of checkboxes from View to Controller将复选框的值从视图传递到控制器
【发布时间】:2014-08-24 08:35:47
【问题描述】:

我有一个视图,其中包含许多复选框。我希望能够将复选框的值传递给控制器​​,然后输出已勾选的 OfficeNames 列表。我不确定如何将多个复选框的值传递回控制器,或者如何根据已勾选的框输出 OfficeNames

查看:

<p>
@using (Html.BeginForm())
{
<p>
    Start Date: @Html.TextBox("StartDate") <br />
    <br />
    End Date: @Html.TextBox("EndDate") <br />
    <br />
    <input type="submit" value="Filter" />
</p>
}

<p>
@foreach (var item in Model.BettingOffices)
{
    <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
    <input type="checkbox" name="selectedShops" value="@item.OfficeName">
}

</p>

控制器:

public class DailyReportController : Controller
{
    private RiskEntities _db = new RiskEntities();

    // GET: /DailyReport/
    public ActionResult Index(DateTime? startDate, DateTime? endDate)
    {

        if (startDate == null || endDate == null)
        {
            var dailyReportModelBlank = new DailyReportModel();
            dailyReportModelBlank.BettingOffices = (from bo in _db.BettingOffices orderby bo.OfficeName select bo ).ToList();
            //dailyReportModelBlank.DailyReports.Add(new DailyReport());
            return View(dailyReportModelBlank);
        }

        var endDateToUse = (DateTime) endDate;
        endDateToUse = endDateToUse.AddDays(+1);


        var dailyReportModel = new DailyReportModel
        {
            DailyReports = (from dr in _db.DailyReports
                where dr.DailyReportDate >= startDate
                      && dr.DailyReportDate <= endDateToUse
                select dr).ToList(),
            BettingOffices = (from bo in _db.BettingOffices select bo).ToList()
        };


        return View(dailyReportModel);
    }

型号:

public class DailyReportModel
{
    private List<DailyReport> _dailyReports = new List<DailyReport>();
    private List<BettingOffice> _bettingOffices = new List<BettingOffice>();

    public List<DailyReport> DailyReports
    {
        get { return _dailyReports; }
        set { _dailyReports = value; }
    }

    public List<BettingOffice> BettingOffices
    {
        get { return _bettingOffices; }
        set { _bettingOffices = value; }
    }
}

BettingOffice 类:

public partial class BettingOffice
{
    public int BettingOfficeID { get; set; }
    public string OfficeName { get; set; }
    public string OfficeCode { get; set; }
    public string IpAddress { get; set; }
    public Nullable<bool> SupportOnly { get; set; }
    public Nullable<int> SisSrNumer { get; set; }
    public Nullable<bool> Local { get; set; }
    public string Server { get; set; }
}

【问题讨论】:

  • 您应该在模型中使用与您的项目类似的复选框定义
  • 你这是什么意思?我是 MVC 新手,所以我不完全理解
  • 我已编辑问题以包含模型
  • 我会看看这个问题,看起来很相似:stackoverflow.com/questions/220020/…

标签: asp.net-mvc checkbox


【解决方案1】:

试试这个:

<p>
    @using (Html.BeginForm())
    {
        <p>
            Start Date: @Html.TextBox("StartDate")
            <br />
            <br />
            End Date: @Html.TextBox("EndDate")
            <br />
            <br />
            <input type="submit" value="Filter" />
        </p>
    }
</p>
<p>
    @foreach (var item in Model.BettingOffices)
    {
        <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
        <input type="checkbox" name="bettingOfficeIDs" value="@item.BettingOfficeID">
    }
</p>

并且在您的操作中,您可以在 bettingOfficeIDs 变量中获取选定的办公室 ID:

 public ActionResult YourActionName(int[] bettingOfficeIDs)

【讨论】:

    【解决方案2】:

    这里需要更改的地方很少。

    1. 如果您希望将值传递给操作方法,它们需要在表单内而不是在表单外

    2. 要让 MVT 将复选框值“理解”为数组(或更复杂的对象),您需要使用它们的 html 名称属性。

    我将在下面做一个演示应用程序,它应该可以帮助你理解它是如何工作的:

    CsHtml: 请注意,您需要将value 属性添加到复选框才能读取它们的值,复选框只有在选中复选框并且值为真时才会获得true,因此javascript .您可以添加尽可能多的复杂对象属性作为隐藏字段,只要您为它们指定与 viewModel 中的对象属性名称匹配的名称即可。在这种情况下,我只传递BettingOfficeID

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    $(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });
    
    <p>
        @using (Html.BeginForm())
        {
            <p>
                Start Date: @Html.TextBox("StartDate") <br />
                <br />
                End Date: @Html.TextBox("EndDate") <br />
                <br />
            </p>
    
            <p>
    
                <input type="checkbox" name="BettingOffices[0].Selected" value="true">
                <input type="hidden" name="BettingOffices[0].BettingOfficeID" value="1">
    
                <input type="checkbox" name="BettingOffices[1].Selected" value="false">
                <input type="hidden" name="BettingOffices[1].BettingOfficeID" value="2">
    
                <input type="checkbox" name="BettingOffices[2].Selected" value="true">
                <input type="hidden" name="BettingOffices[2].BettingOfficeID" value="3">
    
                <input type="checkbox" name="BettingOffices[3].Selected" value="false">
                <input type="hidden" name="BettingOffices[3].BettingOfficeID" value="4">
    
                <input type="checkbox" name="BettingOffices[4].Selected" value="true">
                <input type="hidden" name="BettingOffices[4].BettingOfficeID" value="5">
            </p>
    
            <input type="submit" value="submit"/>
        }
    

    添加到控制器的 Post Action 方法

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(BettingViewModel viewModel)
        {
            return null;
        }
    

    BettingViewModel:我已将 Selected 属性添加到 BettingOffice 类。

    public class BettingViewModel
    {
        public string StartDate { get; set; }
    
        public string EndDate { get; set; }
    
        public List<BettingOffice> BettingOffices { get; set; }
    
    }
    
    public class BettingOffice
    {
        public bool Selected { get; set; }
        public int BettingOfficeID { get; set; }
        public string OfficeName { get; set; }
        public string OfficeCode { get; set; }
        public string IpAddress { get; set; }
        public Nullable<bool> SupportOnly { get; set; }
        public Nullable<int> SisSrNumer { get; set; }
        public Nullable<bool> Local { get; set; }
        public string Server { get; set; }
    }
    

    希望这可以为您节省一些时间。

    【讨论】:

      【解决方案3】:
      View:
      
      @using (Html.BeginForm("Createuser", "User", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
      {
          @Html.AntiForgeryToken()
          <h4>Create a new account.</h4>
      
      
          <div class="form-group">
              @Html.LabelFor(m => m.city, new { @class = "col-md-2 control-label" })
          </div>
          <div class="col-md-10">
              <table>
                  <tr>
                      <td><input type="checkbox" name="city" value="Pune" id="1" />Pune</td>
                      <td><input type="checkbox" name="city" value="Banglore" id="2" />Banglore</td>
                      <td><input type="checkbox" name="city" value="Mumbai" id="3" />Mumbai</td>
                  </tr>
              </table>
              </div>
              <div class="form-group">
                  <div class="col-md-offset-2 col-md-10">
                      <input type="submit" class="btn btn-default" value="Create" />
                  </div>
              </div>
              }
      
      
              [HttpPost]
              public ActionResult Createuser(user user, string [] city)
              {
                  var UserInfo = new user 
                 { Email =user.Email,Password=user.Password,Firstname=user.Firstname };                 
                  return View();
              }
      

      【讨论】:

        【解决方案4】:

        1. 首先,您正在生成具有相同名称的复选框。那么如何在服务器端分别检索它们呢?

        所以声明一些counter,它们会递增并唯一地命名复选框。

        @foreach (var item in Model.BettingOffices)
        {
            int counter=1;
            var checkboxName = "selectedShops" + counter;
        
            <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
            <input type="checkbox" name="@checkboxName" value="@item.OfficeName">
        
            counter++;
        }
        

        2. 现在在您的控制器中提交表单时,将复选框设置为 -

        //Loop through the request.forms
        for (var i = 0; i <= Request.Form.Count; i++)
        {
           var checkboxValue = Request.Form["selectedShops[" + i + "]"];
        
           // Do whatever you want to with this checkbox value
        }
        

        对于勾选的值,您可能会得到 True 值。调试检索到的值以相应地编写更多代码。

        【讨论】:

          【解决方案5】:

          试试下面的

          你的观点是:

          @foreach (var item in Model.BettingOffices)
          {
              <label>@Html.DisplayFor(modelItem => item.OfficeName)</label>
              <input type="checkbox" name="selectedShops" value="@item.OfficeName">
          }
          

          控制器

          [HttpPost]
          public ActionResult Index(FormCollection collection)
          {
               if(!string.IsNullOrEmpty(collection["selectedShops"]))
               {
                  string strSelectedShops = collection["selectedShops"];        
               }
          }
          

          【讨论】:

            【解决方案6】:
            Hi you can get the selected checkbox value using the bellow code it seem working fine fore me,
            
            <script>
            $(document).ready(function()
            {
                $("input[type=checkbox]").click(function()
                {
                        var categoryVals = [];
                        categoryVals.push('');
                        $('#Category_category :checked').each(function() {
                      categoryVals.push($(this).val());
                    });
                    $.ajax({
                        type:"POST",
                        url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
                        data:{'category': categoryVals},
                        success : function(response){
                           //code to do somethng if its success
                        } 
                        });
                }
            }
            </script>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-12-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-03-07
              相关资源
              最近更新 更多