使用AJAX将JSON值绑定到下拉列表

时间:2016-05-26 05:41:45

标签: jquery json ajax asp.net-mvc

我尝试使用.json文件绑定下拉列表。

我的ActionMethod:

 public JsonResult LoadDropdown()
    {
        using (StreamReader sr = new StreamReader(Server.MapPath("~/Scripts/Drop1.json")))
        {
            var users = JsonConvert.DeserializeObject<List<Item>>(sr.ReadToEnd());
            return Json(users, JsonRequestBehavior.AllowGet);
        }

    }

我的AJAX:

$.ajax({
        type: "GET",
        url: "/Home/LoadDropdown",            
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var ddlCustomers = $("[id*=drop1]");
            ddlCustomers.empty().append('<option selected="selected" value="0">--Please select--</option>');
            //alert(data.d);
            $.each(data.d, function () {
                ddlCustomers.append($("<option></option>").val(this['id']).html(this['name']));
            });                
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + "_" + errorThrown);
        }
    });        

我的操作方法返回以下JSON对象

enter image description here

现在在阿贾克斯,我得到了未定义的&#39;当我检查数据时。&#39;在循环之前。还有&#39;数据&#39;拿着像[对象]这样的对象。任何人都可以帮我解决这个错误吗?

2 个答案:

答案 0 :(得分:3)

尝试以下方法:

$.each(data, function (i,v) {
     ddlCustomers.append($("<option</option>",{value:v.id,text:v.name});
});

答案 1 :(得分:0)

我的动作Mathod

            DataTable dt = ds.Tables[0];
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);

<强> AJAX

            $.ajax({
            type: "POST",
            url: "GMCAddEditProduct.aspx/GetDropDownValue",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $("#ContentPlaceHolder1_ddlprotype").empty().append('<option selected="selected" value="0">--Select Product--</option>');
                $.each(JSON.parse(response.d), function (i, v) {
                    $("#ContentPlaceHolder1_ddlprotype").append($("<option></option>", { value: v.ProductTypeID, text: v.Name }))
                });
              },
        });