级联下拉列表mvc 5

时间:2017-04-27 06:26:00

标签: javascript asp.net ajax asp.net-mvc

我一直在研究这几天。我只是想让一些Cascading Dropdownlist工作。我的状态下拉列表没有填充.Ajax没有调用直接错误消息提示显示我做错了什么??

这是我的代码

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; }


    }

这是我的控制器

 [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);
        }    

这里是Register.Cshtml

这是我的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 += "\nState: " + $("#Id option:selected").text();
                alert("good work");
            }
        });
</script>

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

1 个答案:

答案 0 :(得分:0)

我看到了一些潜在的问题:

  • 删除On Build Settings -> Other C flags, set Debug to
  • 使用deferred方法代替成功函数

, and Release to
  • 在完成回调时使用完整签名以获得更多积压

    async: false

  • 使用console.log(数据)而不是alert(“Something Went wrong”)。您将获得更多详细信息。

  • 使用var jqxhr = $.ajax( "example.php" ) .done(function() { alert( "success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "complete" ); }); 代替jqXHR.done(function( data, textStatus, jqXHR ) {});

然后通过更多细节,我们将能够看到做错了什么。

相关问题