级联Dropdownlist MVC 5

I Have been working on this for several days.i,m simply trying to get a couple of Cascading Dropdownlist to work.My dropdownlist for State did not populate.Ajax did not call direct error message alert show what i am doing wrong??

Here is my code

public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [Display(Name ="User Name")]
        public string UserName { get; set; }

        public string Country { get; set; }
        public string State { get; set; }
        public string Role { get; set; }
        public List<SelectListItem> Countries { get; set; }
        public List<SelectListItem> States { get; set; }
        public void CascadingModel() 
        {
            this.Countries = new List<SelectListItem>();
            this.States = new List<SelectListItem>();

        }
        public int CountryId { get; set; }
        public int StateId { get; set; }


    }

here is my controller

 [AllowAnonymous]
        [HttpGet]
        public ActionResult Register()
        {

            RegisterViewModel model = new RegisterViewModel();
            model.Countries = PopulateDropDown("SELECT Id, Name FROM Countries", "Name", "Id");
             Country_Bind();
            //State_Bind();
            return View();
        }
        [HttpPost]
        public JsonResult AjaxMethod(string type, int value)
        {
            RegisterViewModel model = new RegisterViewModel();
            switch (type)
            {
                case "CountryId":
                    model.States = PopulateDropDown("SELECT Id, Name FROM States WHERE CountryId = " + value, "Name", "Id");
                    break;
                    //case "StateId":
                    //    model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities  WHERE StateId = " + value, "CityName", "CityId");
                    //    break;
            }
            ViewBag.State = model;
            return Json(model);
        }

        public void Country_Bind()
        {
            DataSet ds = dblayer.Get_Country();
            List<SelectListItem> countrylist = new List<SelectListItem>();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                countrylist.Add(new SelectListItem { Text = dr["Name"].ToString(), Value = dr["Name"].ToString() });
            }
            ViewBag.Country = countrylist;
        }
        //public void State_Bind()
        //{
        //    DataSet ds = dblayer.Get_State();
        //    List<SelectListItem> statelist = new List<SelectListItem>();

        //    foreach (DataRow dr in ds.Tables[0].Rows)
        //    {
        //        statelist.Add(new SelectListItem { Text = dr["Name"].ToString(), Value = dr["Name"].ToString() });
        //    }
        //    ViewBag.State = statelist;
        //}


        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(int countryId, int stateId)
        {
            RegisterViewModel model = new RegisterViewModel();
            model.Countries = PopulateDropDown("SELECT Id, Name FROM Countries", "Name", "Id");
            model.States = PopulateDropDown("SELECT Id, Name FROM States WHERE CountryId = " + countryId, "Name", "Id");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email};
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, "Candidate");
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            //model.Country =Country_Bind();
            //model.State = State_Bind();
            // If we got this far, something failed, redisplay form
            return View(model);
        }    

here is Register.Cshtml

here is my Register.cshtml

@model Dem4Um_mod.Models.RegisterViewModel

@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>


@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary(true,"", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownList("Country", null, "Please select", new { @class = "form-control" })
          @*@Html.DropDownList("Country", (IEnumerable<SelectListItem>)ViewData["Country"], "Please select", new { @class = "form-control" })*@
        </div>
    </div>
    @*<div>
        <select id="State" style="width:240px">---Select State---</select>
    </div>*@
    <div class="form-group">
        @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.StateId, new SelectList(string.Empty, "Value", "Text"), "Please select", new { @class = "form-control" })
            @*@Html.DropDownListFor(m => m.State, null, "Please select", new { @class = "form-control" })*@
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("select").each(function () {
                if ($(this).find("option").length <= 1) {
                    $(this).attr("disabled", "disabled");
                }

            });
        $("select").change(function () {
                //var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                var id = $(this).attr("Id");
                alert("ddlcountry change");
                $.ajax({
                    type: "POST",
                    url: "Account/AjaxMethod",
                    data: '{type: "' + id + '", value: ' + value + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (response) {
                        alert("Nothing Went wrong");
                        var dropDownId;
                        var list;
                        switch (id) {
                            case "CountryId":
                                list = response.States;
                                DisableDropDown("#StateId");
                                //DisableDropDown("#CityId");
                                PopulateDropDown("#StateId", list);
                                break;
                            //case "StateId":
                            //    dropDownId = "#CityId";
                            //    list = response.Cities;
                            //    DisableDropDown("#CityId");
                            //    PopulateDropDown("#CityId", list);
                            //    break;
                        }

                    },
                    failure: function (response) {
                        alert("Something Went wrong");
                    },
                    error: function (response) {
                        alert("Everything Went wrong");
                    }
                });
            });
        });

    function DisableDropDown(dropDownId) {
            $(dropDownId).attr("disabled");
            $(dropDownId).empty().append('<option selected="selected" value="0">Please select</option>');
        }

    function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        }

    $(function () {
            if ($("#CountryId").val() != "" && $("#Id").val() != "") {
                var message = "Country: " + $("#Id option:selected").text();
                message += "
State: " + $("#Id option:selected").text();
                alert("good work");
            }
        });
</script>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

I'm seeing some potential issues :

  • remove async: false
  • use defered method instead of success function

.

var jqxhr = $.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });
  • use complete signature on done callback to have more backlog

    jqXHR.done(function( data, textStatus, jqXHR ) {});

  • use console.log(data) instead of alert("Something Went wrong"). You will got many more details.

  • use url: @Url.Action("AjaxMethod", "Account") instead of url: "Account/AjaxMethod"

Then with more details, we will able to see what doing is wrong.