我有一个 DropDownListFor
,它保存来 self 的 MVC 模型保存的类中的 Dictionary
的键。当我在该列表中选择一个项目时,我想将 TextArea
的文本设置为字典中的相应值。为此,我尝试使用 JQuery。
我的问题
我好像拿不到字典。要获得它,我必须像这样调用电话:
var fiConfigValues = $('#IdentifiFIConfiguration.Config.Configuration');
在我的 ASP.NET MVC View 中,IdentifiFIConfiguration
是 model
,Config
是一个类,而 Configuration
code> 是我要引用的字典。
但是,代码似乎没有运行,而且我也不知道如何将 var
转换为 Dictionary
以便我可以访问键/值对。
我的问题
在 JQuery 中(如果有办法,甚至在 Razor 中!),我如何访问嵌套在我的 Model
中的几个类中的字典,以便我可以更改值我的 TextArea
?
最佳答案
您实际上是想在客户端进行 View /模型绑定(bind)。通常可以利用 KnockOut.JS 和 KnockOut.Mappings 等框架来帮助创建客户端模型并绑定(bind)到这些模型。
但是,如果您不能使用它或不想弄乱它,您可以手动使用 JQuery 和 JS 执行操作。这可能有点过头了,但我倾向于更结构化和更清晰。一种解决方案可能是迭代您的服务器端模型并生成其客户端模型。然后,通过Jquery 设置一个更改事件,并根据选定的值在集合中定位相应的客户端模型。找到后,使用模型的值更新文本区域。代码如下...
查看代码(带客户端脚本):
@model SoPOC.Models.IdentifiFIConfigurationViewModel
@Html.DropDownListFor(model => model.SelectedConfigId,
new SelectList(Model.Config.ConfigurationList, "Key", "Key", Model.SelectedConfigId),
"Select a Config"
)
<textarea id="configDescription" rows="10"></textarea>
@section Scripts {
<script type="text/javascript">
//array to hold your client side models
ConfigItemList = []
//definition method to query your array
ConfigItemList.GetItem = function (condition) {
for (i = 0, L = this.length; i < L; i++) {
with (this[i]) {
if (eval(condition)) { return this[i]; }
}
}
}
//Your client side item model
ConfigItem = function (key, value) {
var self = this;
self.Key = key;
self.Value = value;
}
//function to update views with model data
function UpdateView(configItem) {
console.log(configItem);
$("#configDescription").val(configItem.Value);
}
//Your C# code to loop over your dictionary and create the client side version
@if(Model.Config.ConfigurationList.Any())
{
foreach(var item in Model.Config.ConfigurationList)
{
//We are mixing C# and JS code here
@:ConfigItemList.push(new ConfigItem(@item.Key, '@item.Value'));
}
}
$(function () {
//bind change event to drop down to update view with model data
$("#SelectedConfigId").change(function () {
UpdateView(ConfigItemList.GetItem("Key === "+ $(this).val()));
});
console.log(ConfigItemList.length);
console.log(ConfigItemList);
});
</script>
}
重要的部分是服务器端对 Dictionary 对象的迭代,生成客户端模型以存储到客户端数组中。之后,您就拥有了可以查询的可用结构中的所有数据。我保留了调试输出以帮助您在需要时进行故障排除。
关于c# - 从 JQuery 中的 MVC 模型获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30807287/