从 JQuery 中的 MVC 模型中获取对象
本文关键字:获取 取对象 模型 MVC JQuery 中的 | 更新日期: 2023-09-27 17:56:07
>我有一个DropDownListFor
,它保存着我的 MVC 模型持有的类中Dictionary
的密钥。当我在该列表中选择一个项目时,我想将TextArea
的文本设置为字典中的相应值。为此,我正在尝试使用JQuery。
我的问题
我似乎无法得到我的字典。要得到它,我必须打一个这样的电话:
var fiConfigValues = $('#IdentifiFIConfiguration.Config.Configuration');
其中IdentifiFIConfiguration
是我的 ASP.NET MVC 视图中的model
,Config
是一个类,Configuration
是我尝试引用的字典。
但是,代码似乎无法运行,而且我也不知道如何将该var
转换为Dictionary
以便我可以访问键/值对。
我的问题
在 JQuery 中(如果有办法,甚至可以在 Razor 中!),如何访问嵌套在Model
内几个类中的字典,以便我可以更改TextArea
的值?
您实际上希望在客户端执行视图/模型绑定。通常可以利用像KnockOut.JS和KnockOut.Mappings这样的框架来帮助创建客户端模型并绑定到这些模型。
但是,如果你不能这样做,或者不想弄乱它,你可以手动使用 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 对象的服务器端迭代,生成要存储到客户端数组中的客户端模型。之后,您将在可以查询的可用结构中拥有所有数据。我保留了调试输出,以帮助您在需要时进行故障排除。
试试这个:
var fiConfigValues = $('@Model.Config.Configuration');
也许你可以这样做
var fiConfigValues = $('@IdentifiFIConfiguration.Config.Configuration');
我认为 fiConfigValues 在 javascript 中变成了一个数组,不确定不是专家有人可能会给出正确的答案。
比你迭代
for(var key in fiConfigValues){
var value = array[key];
console.log(value);
}
那只是我的猜测