栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Javascript / jQuery动态填写下拉列表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Javascript / jQuery动态填写下拉列表

您可以将此下拉列表局部化:

@model MyViewModel@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

然后在主视图中将其包含在某个容器中:

@model MyViewModel...<div id="ddlcontainer">    @Html.Partial("Foo", Model)</div>...

那么您可能会有一个控制器动作,该动作需要一些参数,并根据其值呈现此部分参数:

public ActionResult Foo(string somevalue){    MyViewModel model = ... go ahead and fill your view model    return PartialView(model);}

现在,最后一部分是在发生某些事件时发送AJAX请求以刷新下拉列表。例如,当某些其他ddl的值发生更改(或其他更改,单击按钮或其他操作)时:

$(function() {    $('#SomeOtherDdlId').change(function() {        // when the selection of some other drop down changes         // get the new value        var value = $(this).val();        // and send it as AJAX request to the newly created action        $.ajax({ url: '@Url.Action("foo")', type: 'POST', data: { somevalue: value }, success: function(result) {     // when the AJAX succeeds refresh the ddl container with     // the partial HTML returned by the Foo controller action     $('#ddlcontainer').html(result); }        });    });});

另一种可能性是使用JSON。您的

Foo
控制器操作将仅返回一些包含新键/值集合的Json对象,并且在AJAX请求的成功回调中,您将刷新下拉列表。在这种情况下,您无需将其外部化为单独的部分。例如:

$(function() {    $('#SomeOtherDdlId').change(function() {        // when the selection of some other drop down changes         // get the new value        var value = $(this).val();        // and send it as AJAX request to the newly created action        $.ajax({ url: '@Url.Action("foo")', type: 'POST', data: { somevalue: value }, success: function(result) {     // when the AJAX succeeds refresh the dropdown list with      // the JSON values returned from the controller action     var selectedDeviceModel = $('#SelectedDeviceModel');     selectedDeviceModel.empty();     $.each(result, function(index, item) {         selectedDeviceModel.append(  $('<option/>', {      value: item.value,      text: item.text  })         );     }); }        });    });});

最后,您的Foo控制器动作将返回Json:

public ActionResult Foo(string somevalue){    return Json(new[] {        new { value = '1', text = 'text 1' },        new { value = '2', text = 'text 2' },        new { value = '3', text = 'text 3' }    });}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446510.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号