asp.net-mvc 将复选框的值从视图传递到控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24549988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:45:42  来源:igfitidea点击:

Passing values of checkboxes from View to Controller

asp.net-mvccheckbox

提问by Kevin

I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller, then output a list of the OfficeNames that have been ticked. I am not sure how to pass the values of multiple checkboxes back to the controller, or how to output the OfficeNames based on which boxes have been ticked

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

View:

看法:

<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>

Controller:

控制器:

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);
    }

Model:

模型:

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 Class:

博彩办公室类:

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; }
}

回答by

try this :

尝试这个 :

<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>

And in your Action you can get the selected office ids in bettingOfficeIDs variable:

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

 public ActionResult YourActionName(int[] bettingOfficeIDs)

回答by Matas Vaitkevicius

Few things that need to change here.

这里需要改变的东西很少。

  1. If you want values to be passed to action method they need to be within form not outside

  2. For MVT to 'understand' checkbox values as array (or more complex object) you need to work with their html name attribute.

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

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

I will do demonstration application below that should help you understand how it works:

我将在下面进行演示应用程序,以帮助您了解它是如何工作的:

CsHtml:Notice that you need to add valueattribute to checkboxes to be able to read their values, checkbox gets trueonly when checkbox is ticked and value is true, hence the javascript. You can add as many of complex object properties as hidden fields as long as you give them names that match to the object property names in viewModel. In this case I am only passing BettingOfficeID

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 method to add to controller

添加到控制器的 Post Action 方法

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

BettingViewModel:I have added Selected property to BettingOfficeclass.

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; }
}

enter image description here

在此处输入图片说明

Hope this saves you some time.

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

回答by kamalkishor nagawade

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();
        }

回答by Vikram Singh Saini

1.First of all, you are generating checkboxes with same name. So how you will be able to retrieve them on server end separately?

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

So declare some counterthat gets incremented and name checkboxes uniquely.

因此,声明一些递增的计数器并唯一地命名复选框。

@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.Now on submission of Form in your controller, get checkboxes as -

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
}

For ticked values, you will probably get Truevalue. Debug the retrieved value to write further code accordingly.

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

回答by BJ Patel

Try the following

尝试以下

your View is:

你的观点是:

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

Controller

控制器

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

回答by Karthikeyan Sakthivell

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>