我想用另一个下拉列表填充一个下拉菜单



我尝试了一段视频中的代码,得到了一个错误:

这是我点击下拉菜单显示国家的州时出现的错误

这是我的控制器代码:

public ActionResult Submit()
                    {
                        List<Country> allCountry = new List<Country>();
                        List<State> allState = new List<State>();
                        using (DropDownTestEntities1 dc = new DropDownTestEntities1())
                        {
                            allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
                        }
                        ViewBag.CountryID = new SelectList(allCountry, "CountryID", "CountryName");
                        ViewBag.StateID = new SelectList(allState, "StateID", "StateName");
                        return View();
                    }
         [HttpPost]
         [ValidateAntiForgeryToken] // this is for prevent CSRF Attack
         public ActionResult Submit(Feedback fb)
         {
             List<Country> allCountry = new List<Country>();
             List<State> allState = new List<State>();
             using (DropDownTestEntities1 dc = new DropDownTestEntities1())
             {
                 allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
                 if (fb != null && fb.CountryID > 0)
                 {
                     allState = dc.States.Where(a => a.CountryID.Equals(fb.CountryID)).OrderBy(a => a.StateName).ToList();
                 }
             }
             ViewBag.CountryID = new SelectList(allCountry, "CountryID", "CountryName", fb.CountryID);
             ViewBag.StateID = new SelectList(allState, "StateID", "StateName", fb.StateID);

             if (ModelState.IsValid)
             {
                 using (DropDownTestEntities1 dc = new DropDownTestEntities1())
                 {
                     dc.Feedbacks.Add(fb);
                     dc.SaveChanges();
                     ModelState.Clear();
                     fb = null;
                     ViewBag.Message = "Successfully submitted";
                 }
             }
             else
             {
                 ViewBag.Message = "Failed! Please try again";
             }
             return View(fb);
         }
         [HttpGet]
         public JsonResult GetStates(string countryID = "")
         {
             List<State> allState = new List<State>();
             int ID = 0;
             if (int.TryParse(countryID, out ID))
             {
                 using (DropDownTestEntities1 dc = new DropDownTestEntities1())
                 {
                       allState = dc.States.Where(a => a.CountryID.Equals(ID)).OrderBy(a => a.StateName).ToList();
                     //allState = dc.States.Where(a => a.CountryID.Equals(ID)).OrderBy(a => a.StateName).ToList();
                 }
             }
             if (Request.IsAjaxRequest())
             {
                 return new JsonResult
                 {
                     Data = allState,
                     JsonRequestBehavior = JsonRequestBehavior.AllowGet
                 };
             }
             else
             {
                 return new JsonResult
                 {
                     Data = "Not valid request",
                     JsonRequestBehavior = JsonRequestBehavior.AllowGet
                 };
             }
         }
                }
            }

这是我的型号代码:

 public partial class Feedback
    {
        public int FeedbackID { get; set; }
        [Display(Name = "Full Name")]
        [Required(ErrorMessage = "Please provide your fullname", AllowEmptyStrings = false)]
        public string FullName { get; set; }
        [Display(Name = "Mobile No")]
        public string MobileNo { get; set; }
        [Display(Name = "Country")]
        [Required(ErrorMessage = "Please select country", AllowEmptyStrings = false)]
        public int CountryID { get; set; }
        [Display(Name = "State")]
        [Required(ErrorMessage = "Please select state", AllowEmptyStrings = false)]
        public int StateID { get; set; }
    }

这是我对ajax代码的看法:

@using (Html.BeginForm("Submit", "Feedback", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Feedback</legend>
        @if (ViewBag.Message != null)
        {
            <div style="border:solid 1px black">
                @ViewBag.Message
            </div>
        }
        <div class="editor-label">
            @Html.LabelFor(model => model.FullName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FullName)
            @Html.ValidationMessageFor(model => model.FullName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.MobileNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.MobileNo)
            @Html.ValidationMessageFor(model => model.MobileNo)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.CountryID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.CountryID, @ViewBag.CountryID as SelectList, "Select Country")
            @Html.ValidationMessageFor(model => model.CountryID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.StateID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.StateID, @ViewBag.StateID as SelectList, "Select State")
            @Html.ValidationMessageFor(model => model.StateID)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script language="javascript">
                    $(document).ready(function () {
                        $("#CountryID").change(function () {
                            // this will call when Country Dropdown select change
                            var countryID = parseInt($("#CountryID").val());
                            if (!isNaN(countryID)) {
                                var ddState = $("#StateID");
                                ddState.empty(); // this line is for clear all items from State dropdown
                                ddState.append($("<option></option").val("").html("Select State"));
                                // Here I will call Controller Action via Jquery to load State for selected Country
                                $.ajax({
                                    url: "@Url.Action("GetStates","Feedback")",
                                    type: "GET",
                                    data: { countryID: countryID },
                                    dataType: "json",
                                    success: function (data) {
                                        $.each(data, function (i, val) {
                                            ddState.append(
                                                    $("<option></option>").val(val.StateID).html(val.StateName)
                                                );
                                        });
                                    },
                                    error: function () {
                                        alert("Error!");
                                    }
                                });
                            }
                        });
                    });
    </script>
}

我只想让我的国家选择他们用两者之间的链接来填充我的州。例如,如果我选择南非,它必须只显示豪登省、开普敦等。

请你帮我纠正错误或提供指导,谢谢。

问题1:尝试使用==而不是.Equals(),因为如果CountryID为null,则会引发错误。

问题2:更改

if (Request.IsAjaxRequest())
             {
                 return new JsonResult
                 {
                     Data = allState,
                     JsonRequestBehavior = JsonRequestBehavior.AllowGet
                 };
             }

        return Json(allState, JsonRequestBehavior.AllowGet);

可能的问题3?试试这个作为你的成功函数:

                            success: function (data) {
                                $(data).each(function () {
                                    ddState.append(
                                            $("<option></option>").val(this.StateID).html(this.StateName)
                                        );
                                });
                            },

相关内容

最新更新