【问题标题】:change dropdown list to checkbox in ajax jquery in mvc将下拉列表更改为 mvc 中 ajax jquery 中的复选框
【发布时间】:2017-08-29 09:07:07
【问题描述】:

在我的项目中,我使用了 jquery ajax 的级联下拉列表,它可以工作,但我需要将第二个下拉列表更改为复选框,以根据从第一个下拉列表中选择的地区以及项目选择城市使用复选框选中需要保存在数据库中。但我是 MVC 的新手,我无法以正确的方式提供复选框的代码。

控制器

public ActionResult Create()
    {
        ViewBag.DistrictId = new SelectList(db.DistrictMasters, "Id", "DistrictName");

        return View();
    }

 public JsonResult GetPosts(string id)
    {
        List<SelectListItem> posts = new List<SelectListItem>();
        var postList = this.Getpost(Convert.ToInt32(id));
        var postData = postList.Select(m => new SelectListItem()
        {
            Text = m.PostName,
            Value = m.Id.ToString(),
        });
        return Json(postData, JsonRequestBehavior.AllowGet);
    }

public IList<PostMaster> Getpost(int DistrictId)
    {
        return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList();
    }

  [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "Id,PostId,DistrictId")] Agent agent, FormCollection formdata)
    {
        if (ModelState.IsValid)
        {
            db.Agents.Add(agent);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(agent);
    }

查看创建

@model A.Models.Agent

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
 <div class="form-horizontal">
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })
 <div class="form-group">
        @Html.LabelFor(model => model.PostMaster.DistrictID, "DistrictName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select  --", new { style = "width:250px" }) 
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" })
        </div>
    </div>
 <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<script type="text/javascript">
$(document).ready(function () {
    //District Dropdown Selectedchange event
    $("#DistrictId").change(function () {
        $("#PostMaster").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetPosts")', // Calling json method
            dataType: 'json',
            data: { id: $("#DistrictId").val() },
            // Get Selected post id.
            success: function (posts) {
                $.each(posts, function (i, post) {
                    $("#PostMaster").append('<option value="' + post.Value + '">' +
                         post.Text + '</option>');
                });
            },
            error: function (ex) {
                alert('Failed to retrieve post.' + ex);
            }
        });
        return false;
    })
});

我认为这部分我需要在 jquery 中更改,但我无法做到

 success: function (posts) {
                $.each(posts, function (i, post) {
                    $("#PostMaster").append('<option value="' + post.Value + '">' +
                         post.Text + '</option>');
                });
            },


  <div class="form-group">
        @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" })       

        </div>
    </div>

这是我的代码的一部分。谁能帮我找到解决办法

【问题讨论】:

  • 不清楚你想做什么。您是否要为与所选地区关联的每个城市生成一个复选框,以便您可以选择多个城市?
  • 是的,当我选择地区时,我希望城市作为复选框

标签: jquery ajax asp.net-mvc checkbox drop-down-menu


【解决方案1】:

是的,您可以使用引导多选作为第二个下拉菜单

示例

    <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h4> Cascading dropdown with checkbux - Multiselect</h4>
    <div class="container"> 
        <div class="col-lg-6">
            @Html.DropDownList("Country", (IEnumerable<SelectListItem>)ViewBag.Locations, "Select from", new { @class = "form-control" })
        </div>
        <div class="col-lg-6">
            @Html.DropDownList("City", new SelectList(Enumerable.Empty<SelectListItem>()), new { @class = "multiselect", @multiple = "multiple" })
        </div>
        <br>
        <br>
        <br>
        <br>
        <div>
            <input type="button" id="btnSubmit" value="Submit" class="btn-success" />
        </div>
    </div>
</body>
</html> 

参考资料:

<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap-multiselect.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-multiselect.min.js"></script> 

    <script>

    $(document).ready(function () {
        //once the page load , it load drop down with city - #City 
        var CityDropdown = "";
        $.ajax({
            url: '/MultiSelectController/cityDropDownList',
            type: "GET",
            async: true,
            success: function (result, textStatus, jqXHR) {
           //    console.log("result");
           //    console.log(result);
                $.each(result, function (i, data) {
                    CityDropdown += "<option " + " value=" + data.CityId + ">" + data.CityName + "</option>";
                });
                $('#City').append(CityDropdown);
                $('#City').multiselect('rebuild');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error");
            }
        });

        $('#Country').change(function () {
            // alert('im change country')
            $.ajax({
                url: '/MultiSelectController/cityDropDownListselected',
                type: "GET",
                async: false,
                success: function (result, textStatus, jqXHR) {
                  //  console.log("result");
                  //  console.log(result);
                    var makeCityObj = [];
                    $.each(result, function (i, data) {
                        makeCityObj.push(data.CityId);
                    });
                    $('#City').val(makeCityObj);
                    $("#City").multiselect("refresh");
                    $("#City").multiselect("rebuild");
                }
            });

        });

        $('#btnSubmit').click(function () {
          //  alert("Hi , i'm submit btn ")
            var getSelectCity = $('#City').val();

         //   console.log("getSelectCity");
         //   console.log(getSelectCity);

            //make the child object 
            var cityObj = $('#City').val();
            var CityArray = [];
            if (cityObj != null)
            {
                $.each(cityObj, function (i, data) {
                    var obj = {
                        CityId: parseInt(data),
                    }
                    CityArray.push(obj);
                });
            }

            var sendObj = {
                CountryId : parseInt($('#Country').val()),
                SelectedCity : CityArray,
            }

         //   before send the data to server let check in browser dev tool , cosole.log
            console.log("sendObj");
            console.log(sendObj);

            $.ajax({
                type: 'POST',
                url: '/MultiSelectController/Submit',
                contentType: 'application/json', // data, that we are going to send to server
               // dataType: "text", // retrun type of data
               //   async: false, // by default asyn is true
                traditional: true,
                data: JSON.stringify(sendObj),
                success: function (data, textStatus, jqXHR) {
                    alert('susccess');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error");
                }
            });

        });


        //intialize the multiselection

        $('.multiselect').multiselect({
            enableFiltering: true,
            enableHTML: true,
            buttonClass: 'btn btn-white btn-default btn-sm',
            templates: {
                button: '<button type="button" class="multiselect dropdown-toggle col-sm-12 col-xs-12" data-toggle="dropdown"><span class="multiselect-selected-text"></span> &nbsp;<b class="fa fa-caret-down"></b></button>',
                ul: '<ul class="multiselect-container dropdown-menu"></ul>',
                filter: '<li class="multiselect-item filter"><div class="input-group input-group-sm"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
                filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
                li: '<li><a tabindex="0"><label class="label-sm"></label></a></li>',
                divider: '<li class="multiselect-item divider"></li>',
                liGroup: '<li class="multiselect-item multiselect-group"><label></label></li>'
            },
            maxHeight: 200,
            numberDisplayed: 2,
            includeSelectAllOption: true,
        });
        $("select.multiselect")
                .each(function (i, el) {
                    $(el).parent().find(".multiselect-container>li>a.multiselect-all label").removeClass("label-sm")
                })
        $("select.multiselect").parent().find('.btn-group').addClass("col-sm-12 col-xs-12 no-padding-left no-padding-right");

    })



</script> 

型号:

        public class SubmitViewModel {

            public int CountryId { get; set; }
            public string CountryName { get; set; }
            public List<BPCity> SelectedCity { get; set;  }

        }
        public class BPCity
        {

            public int CityId { get; set; }
            public string CityName { get; set; }




        }
        public class BPCountry
        {
            public int CountryId { get; set; }

            public string CountryName { get; set; }


        } 

控制器:

       public class MultiSelectControllerController : Controller
    {
        // GET: MultiSelectController
        public ActionResult Index()
        {

            //Assigning generic list to ViewBag

            var getCountryList = countryDropDownList();

            List<SelectListItem> ObjList = new List<SelectListItem>();
            foreach (var item in getCountryList)
            {
                ObjList.Add(new SelectListItem
                {
                    Value = "" + item.CountryId,
                    Text = item.CountryName,
                });
            }

            ViewBag.Locations = ObjList;

            return View();
        }
        public List<BPCountry> countryDropDownList()
        {
            List<BPCountry> _ob = new List<BPCountry>();
            for (int x = 1; x < 40; x++)
            {
                BPCountry _cb = new BPCountry
                {

                    CountryId = x,
                    CountryName = "country" + "-" +x,
                };
                _ob.Add(_cb);
            }

            return _ob;
        }


        public ActionResult Submit(SubmitViewModel sendObj) {

            return Json("" ,JsonRequestBehavior.AllowGet);
        }

        public ActionResult cityDropDownListselected()
        {
            List<BPCity> _ob = new List<BPCity>();
            for (int x = 1; x < 4; x++)
            {
                BPCity _cb = new BPCity
                {

                    CityId = x,
                    CityName = "cxcvity" + x,
                };
                _ob.Add(_cb);
            }

            return Json(_ob, JsonRequestBehavior.AllowGet);
        }


        public ActionResult cityDropDownList()
        {
            List<BPCity> _ob = new List<BPCity>();
            for (int x = 1; x < 10; x++)
            {
                BPCity _cb = new BPCity
                {

                    CityId = x,
                    CityName = "cxcvity" + x,
                };
                _ob.Add(_cb);
            }

            return Json(_ob , JsonRequestBehavior.AllowGet);
        } 

快照: UI of View

Receiving data to action method

【讨论】:

  • 控制器 MultiSelectController 和 cityDropDownList 视图中的代码是什么,如何获取多下拉列表的值,我没有正确获取代码
  • 没什么,只是一种方法,将城市作为 json。
【解决方案2】:

与往常一样,首先创建视图模型以在视图中表示您想要的内容

public class AgentVM
{
    ....
    [Required(ErrorMessage = "Please select a District")]
    [Display(Name = "District")]
    public int? SelectedDistrict { get; set; }
    public IEnumerable<SelectListItem> DistrictList { get; set; }
    public IEnumerable<CityVM> Cities { get; set; }
}
public class CityVM
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

并为CityVM 创建一个EditorTemplate。在/Views/Shared/EditorTemplates/CityVM.cshtml

@model CityVM
<div>
    @Html.HiddenFor(m => m.ID)
    @Html.HiddenFor(m => m.Name)
    <label>
        @Html.CheckBoxFor(m => m.IsSelected)
        <span>@Model.Name</span>
    </label>
</div>

以及在您的 ajax 调用中返回的部分视图 - _FetchCities.cshtml

@model AgentVM
@Html.EditorFor(m => m.Cities)

在主视图中

@model AgentVM
@using (Html.BeginForm())
{
    ....
    @Html.LabelFor(m => m.SelectedDistrict)
    @Html.DropDownListFor(m => m.SelectedDistrict, Model.DistrictList, "Please select")
    @Html.ValidationMessageFor(m => m.SelectedDistrict)
    ....
    <div id="cites">
        @Html.EditorFor(m =>m.Cities)
    </div>
    <input type="submit" value="Create" />
}

您的控制器代码将是

public ActionResult Create()
{
    AgentVM model = new AgentVM();
    ConfigureViewModel(model);
    return View(model);
}
[HttpPost]
public ActionResult Create(AgentVM model)
{
    if (!ModelState.IsValid)
    {
        ConfigureViewModel(model);
        return View(model);
    }
    // Get the ID's of the selected cities
    IEnumerable<int> selectedCities = model.Cities.Where(x => x.IsSelected).Select(x => x.ID);
    // Initialize you data model
    // Map its values from the view model
    // Save and redirect
}
public PartialViewResult FetchCities(int id)
{
    // Adjust property names as required
    IEnumerable<CityVM> cities = db.Cities.Where(x => x.DistrictID == id).Select(x => new CityVM
    {
        ID = x.CityID,
        Name = x.CityName
    });
    AgentVM model = new AgentVM()
    {
        Cities = cities
    };
    return PartialView("_FetchCities", model);

}
private ConfigureViewModel(AgentVM model)
{
    model.DistrictList = new SelectList(db.DistrictMasters, "Id", "DistrictName");
    // The following would only be applicable to a view where you editing existing values
    if (model.Cities == null && model.SelectedDistrict.HasValue)
    {
        // Get cities based on SelectedDistrict and map to a collection of `CityVM`
    }
}

最后你的脚本将是

var url = '@Url.Action("FetchCities")';
var cities = $('#cities');
$('#SelectedDistrict').change(function() {
    var selectedCity = $(this).val();
    if (!selectedCity) {
        cities.empty();
        return;
    }
    $.get(url, { id: selectedCity }, function(data) {
        cities.html(data);
    }
})

【讨论】:

  • 它为集合中的每个CityVM 生成正确的html(替代方法是在主视图中使用for 循环,但使用EditorTemplate 使其可重用(并且更少代码)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多