1

我有一个 Html.DropDownListFor、一个文本框和一个包含列表“sourceWatchListParameters”的模型。

我的最终目标是,当在下拉列表中选择一个项目时,使用该特定 sourceWatchList 的属性“DefaultParameter”填充文本框。

$(function() {
    $('select#WatchListDropDown').change(function () {
        var e = document.getElementById("#WatchListDropDown").selectedIndex.value;

        @foreach (var watchlist in Model.sourceWatchListParameters)
        {
            @:if (watchlist.WatchListId == e)
            {
                @: var def = document.getElementById("expDefault");
                @: def.value = watchlist.DefaultParameter;
            }
        }

    })
});

该函数被正确调用,但我无法弄清楚找到正确的 sourceWatchListParameter 并显示其 DefaultParameter 的逻辑/语法。就像现在一样,我在选择的文本框中没有看到任何变化。我确信有一种更简单的方法来重写它。

感谢您的任何指导

4

2 回答 2

2

我想你有这样的事情:

@Html.DropDownListFor(
     m => m.WatchListDropDown, 
     Model.SourceListWatchListDropDown() ...)

这里你只有值('id')和描述,但你可以做这样的事情来获得3个值​​:

<select id="WatchListDropDown" name="WatchListDropDown">
@foreach (var wp in Model.sourceWatchListParameters)
{
   <option value="@wp.WatchListId" data-defparam="@wp.DefaultParameter">@wp.Description</option>
}
</select>

在这种情况下,如果你需要获取默认参数,你只需要这样做:

$(function() {
    $('#WatchListDropDown').bind('change', function () {
        var newValue = $(this).find('option:selected').data('defparam');
        $('#expDefault').val(newValue);;
    })
});

如果您要呈现的页面已经分配了一个值,您可以执行以下操作:

   $('#WatchListDropDown').bind('change', function () {
       ...
   }).trigger('change');

编辑
@Jonesy 解决方案的结果

假设“Model.sourceWatchListParameters”有这个值:

[
 {
    WatchListId = 1,
    Description = "Description 1"
 },
 {
    WatchListId = 3,
    Description = "Description 3"
 },
 {
    WatchListId = 3,
    Description = "Description 3"
 }
]

您的代码如下所示:

$('select#WatchListDropDown').change(function () {

    if ($('#WatchListDropDown').val() == "1")
        $("#expDefault").val("Description 1");
    }

    if ($('#WatchListDropDown').val() == "2")
        $("#expDefault").val("Description 2");
    }

    if ($('#WatchListDropDown').val() == "3")
        $("#expDefault").val("Description 3");
    }
})
于 2013-08-09T18:34:24.997 回答
0

最终得到它:

$('select#WatchListDropDown').change(function () {
        @foreach (var w in Model.sourceWatchListParameters)
        {
            @:if ($('#WatchListDropDown').val() == "@w.WatchListId.ToString()")
            @:{
                @: $("#expDefault").val("@w.Description");
            @:}
        }
    })
于 2013-08-09T18:57:00.593 回答