【问题标题】:DropdownList does not pass value but triggers script. DropdownListFor passes value but does not trigger scriptDropdownList 不传递值但触发脚本。 DropdownListFor 传递值但不触发脚本
【发布时间】:2014-01-23 15:36:47
【问题描述】:

我认为有这个脚本(this 是来源):

<script type="text/javascript" src="../../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("#state").prop("disabled", true);
        $("#country").change(function () {
            if ($("#country").val() != "Please select") {
                var options = {};
                options.url = "/companies/getbolag";
                options.type = "POST";
                options.data = JSON.stringify({ country: $("#country").val() });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (states) {
                    $("#state").empty();
                    for (var i = 0; i < states.length; i++) {
                        $("#state").append("<option>" + states[i] + "</option>");
                    }
                    $("#state").prop("disabled", false);
                };
                options.error = function () { alert("Fel vid bolagshämtning!"); };
                $.ajax(options);
            }
            else {
                $("#state").empty();
                $("#state").prop("disabled", true);
            }
        });
    });

</script>

它会根据第一个下拉列表中的选择填充第二个下拉列表。级联下拉菜单。

此 HtmlHelper 触发脚本,但提交时省略值:

@Html.DropDownList("country", ViewData["kundLista"] as SelectList)

这个反之,它提交值但不触发脚本:

@Html.DropDownListFor(model => model.Kund, ViewData["kundLista"] as SelectList)

我需要它来触发脚本并提交值。我该怎么做?

【问题讨论】:

    标签: c# asp.net-mvc-4 html-helper cascadingdropdown


    【解决方案1】:

    由于您的属性名称是Kund,第二个助手创建了一个选择元素,其中idname 字段设置为Kund。另一方面,您的脚本使用 id country 来处理此选择。所以你有两个选择:

    1. 将脚本中使用的 id 更改为 #Kund:

      $("#Kund").change(function () {
          if ($("#Kund").val() != "Please select") {
      
    2. 使用具有正确名称和 ID 的第一个助手:

      @Html.DropDownList("Kund", ViewData["kundLista"] as SelectList), new {@id="country"})
      

    【讨论】:

    • 我试过tip nr 1,它就像一个魅力!非常感谢! - 我会尽快接受作为答案!
    【解决方案2】:

    如果您查看呈现的 html,下拉列表会创建一个与您的脚本不匹配的 Kund id。我建议在你的下拉列表中放置一个不会改变的类

    @Html.DropDownListFor(x => x.Kund, selectlist, new { @class = "Kund" })
    

    然后在您的脚本中将您的选择器从 #country 更改为 .Kund

    下拉列表会将下拉列表与您的模型联系起来,这就是您获得传递值的原因。对于另一个下拉列表,如果您创建一个列表并将其传递给视图,您可以在那里设置所选项目,这有望为您设置下拉列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多