MVC Javascript基于模型设置文本输入值

MVC Javascript Set Text Input Value Based on Model

本文关键字:置文本 输入 模型 Javascript 于模型 MVC      更新时间:2023-09-26

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

我的最终目标是,当在下拉列表中选择一个项目时,用该特定源WatchList的属性"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的逻辑/语法。和现在一样,我在选择的文本框中没有看到任何变化。我相信有一种更简单的方法可以重写它。

感谢您的指导

我想你有这样的东西:

@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");
    }
})

最终得到了这样的结果:

$('select#WatchListDropDown').change(function () {
        @foreach (var w in Model.sourceWatchListParameters)
        {
            @:if ($('#WatchListDropDown').val() == "@w.WatchListId.ToString()")
            @:{
                @: $("#expDefault").val("@w.Description");
            @:}
        }
    })