0
<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");
4

1 回答 1

0

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

[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很有用。

于 2013-09-09T11:23:52.757 回答