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

时间:2015-11-30 13:53:10

标签: asp.net-mvc-4 entity-framework-4 html.dropdownlistfor

我尝试了视频中的代码并收到错误:

This is the Error when i click my drop down to display the states from country

这是我的控制器代码:

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 个答案:

答案 0 :(得分:1)

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

问题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)
                                        );
                                });
                            },