根据组合框的选定值,我想更新表单中的一些输入元素。组合框填充有 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
属性。您可以访问 text
和 value
属性。
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/