change dropdown list to checkbox in ajax jquery in

2019-09-19 13:44发布

In my project I used cascaded drop down list using jquery ajax and it works, but I need to change the second drop down list to checkbox to select the City based on the districts selected from the first drop down list and also the items selected using checkbox need to be saved in the database. But I am new to MVC and Iam not able to give the code for check box in the correct way.

controller

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

view create

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

I think this part which I need to change in jquery, but I am not able to do it

 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>

this is my part of my code. can anyone please help me to find the solution

2条回答
Emotional °昔
2楼-- · 2019-09-19 14:37

Yes you can use bootstrap multi select for second drop down

Example

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

References:

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

Model:

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


        } 

Controller:

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

SnapShot: UI of View

Receiving data to action method

查看更多
贪生不怕死
3楼-- · 2019-09-19 14:38

As always, start by creating view models to represent what your want in the view

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

And create an EditorTemplate for CityVM. In /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>

and a partial view to be returned in your ajax call - _FetchCities.cshtml

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

And in the main view

@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" />
}

Your controller code will then be

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

And finally your script will be

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);
    }
})
查看更多
登录 后发表回答