MVC4中是否有可用于Dropdownlist的事件(如onChange等)?我们是否必须使用Javascript / jQuery来进行某些操作,例如DropwowlistSelectedItemChanged等?还是只有一种方法可以使用Razor或MVC4功能?

另一方面,能否请您举一些例子,说明如何根据“下拉列表选定值”检索数据并使用该数据更改标签文本?例如,当从下拉列表中选择城市时,我想通过使用选定的城市ID从数据库中获取地址数据,然后在标签上显示检索到的地址。如果您能就上述问题向我澄清,并举例说明实现这一目标,将不胜感激。

控制器:

private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }


视图:

<label>Meeting</label>
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})

最佳答案

尝试这个,

@Html.DropDownListFor(model => model.MyProp, (SelectList)ViewBag.ListItems, new { @id = "MyId", onchange = "MyFunction()" })

<script type="text/javascript">
    function MyFunction() {
        alert('Changed');
        $('#YourLabelId').val('ReplaceWithThisValue');
    }
</script>


或这个

@Html.DropDownListFor(model => model.MyProp, (SelectList)ViewBag.ListItems, new { @id = "MyId"})

<script type="text/javascript">
   $('#MyId').change(function(){
        alert('Changed');
        $('#YourLabelId').val('ReplaceWithThisValue');
    });
</script>

关于jquery - MVC4 Razor中的Dropdownlist SelectedItemChanged事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19450816/

10-12 19:47