C# MVC Javascript基于模型设置文本输入值
我有一个Html.DropDownListFor、一个文本框和一个包含“sourceWatchListParameters”列表的模型 我的最终目标是,当在dropdownlist中选择一个项目时,使用该特定sourceWatchList的属性“DefaultParameter”填充文本框C# MVC Javascript基于模型设置文本输入值,c#,javascript,asp.net-mvc,razor,model,C#,Javascript,Asp.net Mvc,Razor,Model,我有一个Html.DropDownListFor、一个文本框和一个包含“sourceWatchListParameters”列表的模型 我的最终目标是,当在dropdownlist中选择一个项目时,使用该特定sourceWatchList的属性“DefaultParameter”填充文本框 $(function() { $('select#WatchListDropDown').change(function () { var e = document.getElemen
$(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>
如果要呈现页面的用户已指定值,则可以执行以下操作:
$('#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");
@:}
}
})
什么是
watchlist
以及为什么要混合使用JS和jQuery?我想我混合使用它们是因为我很困惑,好吧,“DefaultParameter”是什么?通过这个解决方案,您的javascript代码中包含了所有编写的项目以及每个项目的所有“如果”对不起,您的意思是什么?我会在回答中回答您。
$('select#WatchListDropDown').change(function () {
@foreach (var w in Model.sourceWatchListParameters)
{
@:if ($('#WatchListDropDown').val() == "@w.WatchListId.ToString()")
@:{
@: $("#expDefault").val("@w.Description");
@:}
}
})