级联下拉列表,不提交表格

时间:2015-12-17 08:51:09

标签: c# asp.net-mvc

我为国家和城市创建了一个Cascading DropDownList。它在检索数据时工作正常但是当我尝试提交表单时,City下拉列表变空而不发布数据..这是我的代码...(我跟着this链接)

有人能告诉我这里有什么问题 这就是我所做的......

控制器

[AcceptVerbs(HttpVerbs.Get)]
    public ActionResult GetAllCitiesByCountryId(string countryId)
    {
        if (String.IsNullOrEmpty(countryId))
        {
            throw new ArgumentNullException("countryId");
        }
        int id = 0;
        bool isValid = Int32.TryParse(countryId, out id);
        var cities = _CountryRepository.GetAllCitiesByCountryId(id);
        var result = (from s in cities
                      select new
                      {
                          id = s.ID,
                          name = s.DESCRIPTION
                      }).ToList();

        return Json(result, JsonRequestBehavior.AllowGet);
    }

查看

$(function () {
        $("#CountryID").change(function () {
            var selectedItem = $(this).val();
            var cities = $("#CityID");
            var citiesProgress = $("#cities-loading-progress");
            citiesProgress.show();
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetAllCitiesByCountryId"))",
                data: { "countryId": selectedItem },
                success: function (data) {
                    cities.html('');
                    $.each(data, function (id, option) {
                    cities.append($('<option></option>').val(option.id).html(option.name));
                    });
                citiesProgress.hide();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Failed to retrieve cities.');
                citiesProgress.hide();
            }
            });
            //$('#CityID').change(function() {
            //    this.form.submit();
    });
    });

<div class="form-group">
        @Html.LabelFor(model => model.CityID, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CityID, Model.City, "", new { @class = "form-control" })
            <span id="cities-loading-progress" style="display: none;">Please wait..</span>
            @Html.ValidationMessageFor(model => model.CityID, string.Empty, new { @class = "text-danger" })
        </div>
    </div>

1 个答案:

答案 0 :(得分:0)

您可以在RouteConfig.cs文件中添加此代码:

routes.MapRoute("GetAllCitiesByCountryId",
                "ControllerName/GetAllCitiesByCountryId/",
                new { controller = "ControllerName", action = "GetAllCitiesByCountryId" },
                new[] { "CountryCityApplication.Controllers" });

这是因为你使用了这个:

url: "@(Url.RouteUrl("GetAllCitiesByCountryId"))",