如何获取checkboxlist的选定值,并使用jquery将该值从视图传递给控制器

时间:2017-07-25 06:12:24

标签: asp.net asp.net-mvc checkbox

视图:

 @using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
     {
        foreach (var item in Model.QualityModel)
        {
       <li><input type="checkbox" name="qualitycheck"/><span>item.qualityName</span></li>
        }
   }

控制器:

public ActionResult Searchbyquality(string[] qualitycheck )
{
           //code of searching

}

我想将多个选定值传递给控制器​​

1 个答案:

答案 0 :(得分:0)

您的观看代码应为:

 @using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
     {
    foreach (var item in Model.QualityModel)
                {
                    <div class="checkbox">
                        <label>
                            <input type="checkbox"
                                   name="qualitycheck"
                                   value="@item.qualityName" /> @item.qualityName
                            </label>
                        </div>
                }
                @*<div class="form-group text-center">
                    <input type="submit" class="btn btn-primary" value="Submit" />
                </div>*@
}

如果没有Submit button,您必须添加jQuery代码来调用控制器操作:

$( document ).ready(function() {

 $(":checkbox").change(function() {
        if(this.checked) {
            var qualitycheck_data = { 'qualitycheck': [] };

            $('input:checked').each(function ()
            {
                if(this.name == 'qualitycheck') qualitycheck_data['qualitycheck'].push($(this).val());

            });
            var path = "/Health/Searchbyquality";
            $.ajax({
                url: path, type: "POST", cache: "false",
                dataType: "json", contentType: "application/json; charset=utf-8",
                data: JSON.stringify(qualitycheck_data),
                traditional: true,
                converters: {'text json': true}
            }).success(function (responseText) {
               //Success result 
               window.location.assign(responseText); 
            }).error(function (responseText){
                swal("Error!", "Test 1", "error");
            });
            //swal("Error!", "Test 2", "error");
        }
    });
});

您的控制器操作:

[HttpPost]
public ActionResult Searchbyquality(string[] qualitycheck )
{
           //code of searching
   return View("");
}

干杯!!