gpt4 book ai didi

javascript - 在没有 Ajax 的情况下使用 Javascript 中的 C# 对象的属性更新输入元素?

转载 作者:行者123 更新时间:2023-11-30 05:51:16 27 4
gpt4 key购买 nike

根据组合框的选定值,我想更新表单中的一些输入元素。组合框填充有 List<Person>从 Controller 通过 ViewBag 传递:

@Html.DropDownListFor(x => x.Person, new SelectList(ViewBag.Persons, "Id", "Name"), "Choose", new { id = "comboBox" })

现在我想知道是否可以在不执行 Ajax 请求的情况下更新元素:

$(function () {
$('#comboBox').change(function () {
var person = this.options[this.selectedIndex];
document.getElementById("Age").value = person.Age; // fault!
});
});

换句话说:有没有办法将 .Net 对象传递给 JavaScript?也许通过一个额外的图书馆?或者我是否通过创建 SelectList 来丢失所有信息?对于组合框?

最佳答案

person 是一个 HTMLOptionElement。它没有 Age 属性。您可以访问 textvalue 属性。

document.getElementById("Age").value = person.value;

在您的页面中插入一个 Person 对象的 Javascript 数组,然后您可以通过 Id 获取选定的 Person 并根据需要使用它的 Age 属性。

<script type="text/javascript">
var people = [{"id": 1, "name": "foo", "age": 10}, {"id": 2, "name": "bar", "age": 20}, {"id": 3, "name": "baz", "age": 30}];

function getPerson(id) {
for(var i=0, max = people.length;i<max;i++) {
if(people[i].id === id) {
return people[i];
}
}
return null;
}
</script>

关于javascript - 在没有 Ajax 的情况下使用 Javascript 中的 C# 对象的属性更新输入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14739741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com