dropdown menu populate another c# mvc json ajax

佐手、 提交于 2021-02-10 05:12:32

问题


Below is my code, I am not sure what i am doing wrong?

Ajax json jquery code

function FillCity() {
    var countryid = $("select[name$='.countryid']").val();     //<---- this is dynamic
    $.ajax({
        url: "Controller/FillMyCity",
        type: "POST",
        dataType: "json",           
        data: { country: countryid } ,           
        success: function (city) {
            $("select[name$='.cityid']").html(""); // <--- this is dynamic
            $.each(city, function (i, pp) {
                $("select[name$='.cityid']").append(
                    $('<option></option>').val(pp.cityid).html(pp.name));
            });               
        },
        error: function (err) {                
            alert(err);
        }
    });
}

Controller method

public JsonResult FillMyCity(int country)
{

    var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
    {
        cityid = item.cityid,
        name = item.name
    }).AsQueryable();
    return Json(cities, JsonRequestBehavior.AllowGet);
}

View

@Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { @class = "form-control countries", @id = "mycountry" + i + "", @onchange = "FillCity()" })
@Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { @class = "form-control cities", @id = "mycity" + i + "" })      

Output

EmployeeName  Country                       City
Jenny         ddl of countries              ddl of cities     
John          ddl of countries              ddl of cities

Problem 1: When I select country for Jenny, the cities ddl for both Jenny + John both get populated with Jenny's Country's cities, but it should only just applied for Jenny. When I select country for John the cities ddl list doesn't get populate So only Jenny's works, John doesn't

Problem 2: Since it is a dynamic json jquery appended html, I am unable to save the cities value, this is due to the fact that it is dynamic and doesn't appear in the view source.


回答1:


Your use of $("select[name$='.countryid']").val(); will only ever select the value of the first element that has a name attribute ending with .countryid.

In addition, you use of DropDownList("Country[" + i + "].countryid", ...) is not the correct way to generate controls for a collection and its unlikely that will ever bind correctly to your model, however you have not shown the model so that cannot be fixed, so based on your current code, your view should be

<div class="container">
    @Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { @class = "form-control countries" })
    @Html.DropDownList("City[" + i + "].cityid", Enumerable.Empty<SelectListItem>(), new { @class = "form-control cities" })
</div>

and the script

$('.countries').change(function() {
    var country = $(this).val();
    var cities = $(this).next('.cities'); // get the associated cities dropdownlist
    cities.empty(); // clear existing options
    $.ajax({
        url: '@Url.Action("FillMyCity")', // do not hard code url's
        type: "POST",
        dataType: "json",           
        data: { country: country } ,           
        success: function (data) {
            if (data) {
                cities.append($('<option></option>').val('').text('Select city'));
                $.each(data, function (index, item) {
                    cities.append($('<option</option>').val(item.cityid).html(item.name));
                });
             } else {
                 // oops
             }            
        },
        error: function (err) {                
            alert(err);
        }
    });
});

and finally, return a collection of anonymous objects containing only the data you need in the view to avoid sending extra data that will not be used

public JsonResult FillMyCity(int country)
{
    // No need for .ToList()
    var cities = db.Cities.Where(x => x.countryid == country).Select(item => new
    {
        cityid = item.cityid,
        name = item.name
    });
    return Json(cities); // its a POST so no need for JsonRequestBehavior.AllowGet
}


来源:https://stackoverflow.com/questions/36672155/dropdown-menu-populate-another-c-sharp-mvc-json-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!