2

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

@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组合框来丢失所有信息?

4

1 回答 1

1

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

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

在您的页面中插入一个 Person 对象的 Javascript 数组,然后您可以Person通过 Id 获取选择的对象并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>

于 2013-02-06T22:38:46.857 回答