使用ajax返回值填充下拉列表

时间:2013-09-09 07:40:01

标签: asp.net-mvc jquery razor

<script>
    $(document).ready(function () {

        $('#dropdown').change(function () {
            var val = $(this).val();
                $.post("@Url.Action("GetServices","vas")", { catId: $(this).val() }, function (data) {
                    $('#dropdownServices').val(data);// here how to fill dropdownlist with the returned selected item.
                });

        });
    });
</script>

HTML

 @Html.DropDownListFor(x => x.SelectedItem, new SelectList(Model.ListOfServices, "Value", "Text"),"choose an Option");

1 个答案:

答案 0 :(得分:0)

假设您的控制器操作返回包含ValueText属性的JSON结果:

[HttpPost]
public ActionResult GetServices(int catId)
{
    // This is probably coming from a database or something but you should
    // respect the JSON structure. Make sure you project your collection
    // to a list of elements where each element contains Value and Text properties
    // because they will be used on the client to bind the dropdown

    return Json(new[]
    {
        new { Value = "1", Text = "item 1" },
        new { Value = "2", Text = "item 2" },
        new { Value = "3", Text = "item 3" },
    });
}

你可以像这样绑定下拉列表:

var url = '@Url.Action("GetServices", "vas")';
$.post(url, { catId: $(this).val() }, function (data) {
    var ddl = $('#dropdownServices');
    ddl.empty();
    $.each(data, function() {
        ddl.append(
            $('<option/>', {
                value: this.Value,
                html: this.Text
            })
        );
    });
});

另外,请确保您已在下拉列表中应用了正确的id属性,以便此处使用的$('#dropdownServices')选择器实际上会返回一些内容:

@Html.DropDownListFor(
    x => x.SelectedItem, 
    new SelectList(Model.ListOfServices, "Value", "Text"),
    "choose an Option",
    new { id = "dropdownServices" }
);

顺便说一句,如果您要构建一些级联下拉列表,您可能会发现following answer很有用。