DropdownList不传递值但会触发脚本。 DropdownListFor传递值但不触发脚本

时间:2014-01-23 15:36:48

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

我在我的视图中有这个脚本(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)

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

2 个答案:

答案 0 :(得分:1)

由于您的属性名称为Kund,因此第二个帮助程序会创建一个select idname字段设置为Kund的select元素。另一方面,您的脚本使用标识country来解决此选择。所以你有两个选择:

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

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

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

答案 1 :(得分:0)

如果你看一下渲染的html下拉列表,就会创建一个与你的脚本不匹配的Kund id。我建议在你的下拉菜单上放一个不会改变的课程

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

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

下拉列表会将下拉列表绑定到您的模型,这就是您获得传递值的原因。对于另一个下拉菜单,如果您创建一个List并将其传递给视图,您可以在那里设置所选项目,并希望为您设置下拉列表