用于刷新下拉列表的ajax回发方法

时间:2016-01-08 15:28:46

标签: javascript c# jquery asp.net ajax

Scoop ......

我有一个下拉列表,可能无法显示您正在寻找的特定选项。我添加了一个带弹出模式的按钮,用于输入要添加到下拉列表的字段。它运行完美,但我需要添加一个ajax回发方法,以便在用户点击进入后刷新列表。我不想刷新整个页面,只是列表。任何帮助?

控制器

        public ActionResult AddLeadSource()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AddLeadSource(string name)
    {
        LeadSource ls = new LeadSource();
        ls.Name = name;
        db.LeadSources.Add(ls);
        db.SaveChanges();
        return Json(new { success = true });
    }

JS

<script>
$("#AddNew").change(function () {
    var name = $("#Name").val();
    // var order = $("#DisplayOrder").val();

    $.ajax({
        type: 'POST',
        dataType: 'json',
        cache: false,
        url: '/Admin/LeadSource/AddLeadSource',
        data: { name: name },
        success: function (response) {
            //alert("Success " + response.success);
            $('#FollowUpNotes').kendoWindow('destroy');
            // Refresh the DropDown <-- Heres where I need some help!


        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error - ' + errorThrown);
        }
    });
});

2 个答案:

答案 0 :(得分:0)

我强烈建议您查看jQuery UI的自动完成小部件。那就是说,

 $('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">

然后你只需要根据响应数据构建新的

        for (var o in data) {
            if (data[o].Value != undefined) {
                $('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
            }
        }

我在AJAX的.done()回调中执行此操作:

    .done(function (data) {
        //above code
    }

根据您发回的数据的性质,您可能需要以不同方式循环显示它。我是一个具有值和显示属性的对象数组(在我的例子中,帐号和帐户名称)。

//server side controller
    var query = @"
    Select
        SubString([mn_no], 0, 6) As Value,
        RTRIM([acct_desc]) As Display
    From [some_table]";
            return con.Query(query, new { AccountNumber = accounts.Select(x =>
            {
                return new { Value = x.Value, Display = x.Display };
            });

答案 1 :(得分:0)

在您的Ajax调用的成功函数中添加以下内容:

$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();

通过这种方式,您的下拉列表将调用read函数并重新加载所有数据。我假设你的下拉列表是通过读取调用绑定的。