微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 ASP.Net MVC 级联依赖DropDownList

如何解决使用 ASP.Net MVC 级联依赖DropDownList

我已经使用 ASP.Net MVC 实现了 Cascading (Dependent) DropDownList。

这是tutorial

现在我需要在 ASP.Net MVC 的索引页面上插入数据和重定向显示警报消息框。

为了在使用 MysqL 数据库中的存储过程插入数据后在 asp.net mvc 中显示警报消息,我编写了如下所示的代码

<script type="text/javascript">
    $(function () {
       var msg = '@ViewData["result"]';
          if (msg > 0)
          {
             alert("User Details Inserted Successfully");
             window.location.href = "@Url.Action("Index","Home")";
          }
});
</script>

数据在数据库表中正确注册,插入数据后显示提示框。

但是重定向到 index.cshtml 不起作用,因为除了第一个正确填充的 DropDownList 之外,表单上的所有 DropDownList 都是空的。

window.location.href = "@Url.Action("Index","Home")";

我的意思是所有其他(填充的级联)DropDownList 都已启用但为空。

我需要重定向到索引操作页面并能够重新加载新记录,使用这种重定向是不可能的,因为填充的级联 DropDownList 保持为空...而不是禁用并从第一个下拉列表的值填充...>

如何解决这个问题?

谢谢。

更新 2021-01-02

@section Scripts {

    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/DatePicker.js");
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
        $(function () {
            var msg = '@ViewData["result"]';
            console.log(msg);
              if (msg > 0)
              {
                  alert("User Details Inserted Successfully");
                  var url = "@Url.Action("Index","Home")";
                  window.location.href = url;
              }
    });
    </script>

    <script src="Scripts/jquery-1.10.2.js"></script>

    <script type="text/javascript">
        jQuery(function ($) {
            $.validator.addMethod('date',function (value,element) {
                    if (this.optional(element)) {
                        return true;
                    }
                    var ok = true;
                    try {
                        $.datepicker.parseDate('dd/mm/yy',value);
                    }
                    catch (err) {
                        ok = false;
                    }
                    return ok;
                });

        $("#thedate").datepicker(options);

        $(function () {
            $(".loading").hide();
            $("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");
                $.ajax({
                    type: "POST",url: "/Home/AjaxMethod",data: '{type: "' + id + '",value: "' + value + '"}',contentType: "application/json; charset=utf-8",dataType: "json",success: function (response) {
                        var dropDownId;
                        var list;
                        switch (id) {

                            case "CountryId":
                                list = response.States;

                                disableDropDown("#TicketId");
                                disableDropDown("#CityId");

                                dropDownId = "#TicketId";
                                list = response.Ticket;
                                PopulateDropDown("#TicketId",list);

                                break;

                            case "TicketId":
                                list = response.States;
                                disableDropDown("#StateId");
                                PopulateDropDown("#StateId",list);

                                break;

                            case "StateId":
                                dropDownId = "#CityId";
                                list = response.Cities;
                                disableDropDown("#CityId");
                                PopulateDropDown("#CityId",list);

                                dropDownId = "#CityId2";
                                list = response.Cities2;
                                PopulateDropDown("#CityId2",list);

                                $("#GPS").val(response.GPS);

                                break;
                        }

                    },failure: function (response) {
                        alert(response.responseText);
                    },error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });

        function disableDropDown(dropDownId) {
            $(dropDownId).attr("disabled","disabled");
            $(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
        }

        function PopulateDropDown(dropDownId,list) {
            var modal = $('<div />');
            modal.addClass("modalBackground");
            $('body').append(modal);
            var loading = $(".loading");
            loading.show();
            var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2,0);
            var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2,0);
            loading.css({ top: top,left: left });
            setTimeout(function () {
                if (list != null && list.length > 0) {
                    $(dropDownId).removeAttr("disabled");
                    $.each(list,function () {
                        $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                    $(".loading").hide();
                    $('.modalBackground').remove();
                }
            },1000);
        }

    </script>
}

更新控制器

    [HttpPost]
    public ActionResult Index(PersonModel person)
    {                
        MTsqlinsert(person); //Insert values in the database

        if (ModelState.IsValid)
        {
            PersonModel personModel = new PersonModel();

            person.Countries = PopulateDropDown("SELECT CountryId,CountryName FROM Countries","CountryName","CountryId");
            person.States = PopulateDropDown("SELECT StateId,StateName FROM States WHERE CountryId = " + countryId,"StateName","StateId");
            person.Cities = PopulateDropDown("SELECT CityId,CityName FROM Cities WHERE StateId = " + stateId,"CityName","CityID");

            ViewData["result"] = "1";
            return RedirectToAction("Index");
        }
        return View(person);
    }

    [HttpGet]
    [OutputCache(NoStore = true,Duration = 60,varyByParam = "*")]
    public ActionResult Index()
    {
        PersonModel personModel = new PersonModel
        {
           Countries = PopulateDropDown("SELECT CountryId,"CountryId");
        };

        return View(personModel);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。