0

我有 2 个下拉菜单,第一个是Country,第二个是City.

我尝试使用级联下拉列表进行搜索,当显示结果时,下拉列表的值不再为空。例如,我选择Austria in Countryand Viennain City,当结果显示时,在下拉列表Country中的值仍然是Austriaand Cityis Vienna

我尝试使用 javascript,但我不能。这是我的代码:

控制器

        [HttpGet]
        public ActionResult Customer()
        {
            List<Country> country = _CustomerService.GetCountryForDropDown();
            CustomerViewModel model = CustomerBuilder.BuildCountries(country);
            return View(model);
        }

        [HttpPost]
        public ActionResult Customer(CustemerRequest request, FormCollection frm)
        {
            if (ModelState.IsValid)
            {                
                List<Organization> ListOrganization = _CustomerService.GetOrganization(request.InfotechCode, request.CustomerName, frm["DDCountryModel"], frm["ddlCity"]);
                List<Country> country = _CustomerService.GetCountryForDropDown();
                cvm = CustomerBuilder.Build(ListOrganization,country);
                cvm.Request = request;
                return RedirectToAction("Result", new { Page = 1 });
            }
            return View(new CustomerViewModel { Request = request, ListCustomer = null });
        }

        [HttpGet]
        public ActionResult Result(int Page)
        {
            if (cvm != null)
            {
                return View("Customer", cvm);
            }
            else
                return RedirectToAction("Customer", new { Request = Request });
        }

        [HttpPost]
            public ActionResult GetCityByCountryForDropDown(int CountryID, FormCollection frm)
            {
                List<City> city = _CustomerService.GetCityForDropDown();
                ITTOS.ViewModel.Customer.CustomerViewModel model = ITTOS.ViewModel.Builder.CustomerBuilder.BuildCities(city);

                List<ITTOS.ViewModel.Customer.DDCity> getCityFromCountry = new List<ITTOS.ViewModel.Customer.DDCity>();
                getCityFromCountry = model.DDCityModel.Where(r => r.CountryID == CountryID).ToList();
                SelectList CityinCountry = new SelectList(getCityFromCountry, "CityID", "CityName", 0);
                return Json(CityinCountry);
            }

视图模型

[Serializable]
    public class CustemerRequest
    {
        public string InfotechCode { get; set; }
        public string CustomerName { get; set; }
        public int? CountryID { get; set; }
        public int? CityID { get; set; }
    }

    public class DDCountry
    {
        public int CountryID { get; set; }
        public string CountryName { get; set; }
    }

    public class DDCity
    {
        public int CountryID { get; set; }
        public int CityID { get; set; }
        public string CityName { get; set; }
    }

查看模型生成器

public static CustomerViewModel BuildCities (List<City> city)
        {
            CustomerViewModel model = new CustomerViewModel();
            model.DDCityModel = new List<DDCity>();

            foreach (var cities in city)
            {
                DDCity ct = new DDCity
                {
                    CityID = cities.CityID,
                    CityName = cities.CityName,
                    CountryID = cities.CountryID
                };
                model.DDCityModel.Add(ct);
            }
            return model;
        }

        public static CustomerViewModel BuildCountries(List<Country> country)
        {
            CustomerViewModel model = new CustomerViewModel();
            model.DDCountryModel = new List<DDCountry>();

            foreach (var countries in country)
            {
                DDCountry ct = new DDCountry
                {
                    CountryID = countries.CountryID,
                    CountryName = countries.CountryName
                };
                model.DDCountryModel.Add(ct);
            }
            return model;
        }

和我的看法

 <script type="text/javascript">
        function GetCity(_CountryID) {
            var SelectedCountry = $('#CountryID').val(_CountryID);
                var procemessage = "<option value='0'> Please wait...</option>";
                $('#ddlCity').html(procemessage).show();
                var url = "/Json/GetCityByCountryForDropDown/";


                $.ajax({
                    url: url,
                    data: { CountryID: _CountryID },
                    cache: false,
                    type: "POST",
                    success: function (data) {
                        var markup = "<option value='0'>Select City</option>";
                        for (var x = 0; x < data.length; x++) {
                            markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                        }
                        $('#ddlCity').html(markup).show();
                    },
                    error: function (reponse) {
                        alert("error : " + reponse);
                    }
                });
        }

        function GetValue(_CityID)
        {
            $('#CityID').val(_CityID);
        }
    </script>

 @Html.HiddenFor(mdl => mdl.Request.CountryID, new { id = "CountryID" })
                @Html.HiddenFor(mdl => mdl.Request.CityID, new { id = "CityID" })
                @using (Html.BeginForm("", ""))
                {
                    @Html.Label("Country - City")
                    @Html.DropDownListFor(m => m.DDCountryModel, new SelectList(Model.DDCountryModel, "CountryID", "CountryName"),"Select Country", new { @id = "ddlstate", @style = "width:100px;margin-left:36px;", @onchange = "javascript:GetCity(this.value);" })
                    <select id="ddlCity" name="ddlCity" style="width: 100px; margin-left: 5px;" onchange="javascript:GetValue(this.value);"></select>
                }

有人能帮助我吗

4

1 回答 1

0

这是一个相当简单的例子,希望对你有所帮助。根本不需要隐藏字段。_Adapter 类代表我的数据库访问层的一部分(因为我使用 EF 和 PostgreSQL),“Companies”类基本上是数据表实体。

楷模:

public class CompanyModel {

    public CountryModel Country{ get; set; }

    public CityModel City { get; set; }

    public SelectList AvailableCountries {
        get {
            return new SelectList(
                CountryAdapter.GetCountries(),
                "Id",
                "Name"
                );
        }
    }

    public SelectList AvailableCities {
        get {
            return new SelectList(
                CityAdapter.GetCities(Country.Id),
                "Id",
                "Name"
                );
        }
    }

    public CompanyModel(Companies company) {// from the database layer
        Country = new CountryModel (company.CountryId, company.Countries.Name);
        City = new CityModel(company.CityId, company.Cities.Name);
}


public class CountryModel {

    public int Id { get; set; }

    public string Name { get; set; }

    public CountryModel() {
    }

    public CountryModel(int id, string name) {
        Id = id;
        Name = name;
    }
}


public class CityModel {

    public int Id { get; set; }

    public string Name { get; set; }

    public CityModel() {
    }

    public CityModel(int id, string name) {
        Id = id;
        Name = name;
    }

控制器:

    [HttpGet]
    public ActionResult Edit(int id) {
        return View(new CompanyModel(CompanyAdapter.GetCompany(id)));
    }

    [HttpPost]
    public ActionResult Edit(CompanyModel company) {
        if (ModelState.IsValid)
           // save in the db

        return View(company);
    }

    /// <param name="id">CountryId</param>
    public ActionResult GetCities(int id) {
        //retrieve from db
        var cities = CityAdapter.GetCities(id)
            .Select(city => new { id = city.Id, name = city.Name })
            .ToList();

        return Json(cities, JsonRequestBehavior.AllowGet);
    }

看法:

@model ServbitOffice.Models.CompanyModel
@using (Html.BeginForm()) {
    @Html.DropDownListFor(company => company.Country.Id, Model.AvailableCountries, new { onchange = "LoadCities()" })
    @Html.DropDownListFor(company => company.City.Id, Model.AvailableCities)
<input type="submit" value="Save"/>
}

脚本(也在上一个视图中):

<script type="text/javascript">
    function LoadCities() {
        var selectedCountryId= $("#Country_Id").val();

        $.ajax({
            url: "@Url.Action("GetCities")",
            type: 'GET',
            data: { id: selectedCountryId},
        }).done(function (result) {
            var cities = $('#City_Id');
            cities.empty();
            $.each(result, function (index, item) {
                cities.append(
                    $('<option />', {
                        value: item.id,
                        text: item.name
                    })
                );
            });
        });
    };
</script>
于 2013-08-02T08:13:20.173 回答