填充选择下拉列表,每行为空

时间:2014-02-12 13:56:04

标签: knockout.js

我正在尝试填充下拉列表,但它不起作用。 我错过了什么吗? 我的下拉列表填充,但它不显示数据库名称,每行只有空白。

如果我只使用<“select data-bind =”选项:数据库“>我的下拉列表填充[object Object]。

我的控制器返回的json结果:

{
   "success":true,
   "databases":"[\r\n  {\r\n    \"Id\": \"1\",\r\n    \"Name\": \"Test1\"\r\n  },\r\n  {\r\n    \"Id\": \"2\",\r\n    \"Name\": \"Test2\"\r\n]"
}

感谢正手!

代码:

 <select data-bind="options: databases, optionsText: 'Name', optionsValue: 'Id', value: 'Id', optionsCaption: 'Choose DB'"></select>

 <script type="text/javascript">
 var data = [];

var DatabaseViewModel = function (data) {
    this.Id = data.Id;
    this.Name = data.Name;
};

var ViewModel = function () {
    var self = this;
    self.databases = ko.observableArray(data);

    $(function () {
        // on this click event, we popular the observable array
        $('#load').click(function () {
            $.ajax({
                url: "@Url.Action("LoadDatabases", "StoredProcedure")",
                type: "POST",
                dataType: 'json',
                async: false,
                contentType: "application/json",
                success: function (response) {
                    if (response.success) {
                        var array = [];
                        $.each(response.databases, function (index, value) {
                            array.push(new DatabaseViewModel(value));
                        });
                        self.databases(array);
                    } else {
                        alert(response.message);
                        window.location.href = response.redirectUrl;
                    }
                }
            });
        });
    });
};

控制器中的LoadDatabases操作:

   [HttpParamAction]
         [HttpPost]
           public JsonResult LoadDatabases()
          {
            try
              {
                  var dbs = _configService.GetAllDatabases().ToList();

            var databaseList = new List<DatabaseModel>();


            foreach (var db in dbs)
            {
                var model = new DatabaseModel { Id = db.Id.ToString(CultureInfo.InvariantCulture), Name = db.Name };
                databaseList.Add(model);
            }

            return Json(new
            {
                success = true,
                databases = JsonConvert.SerializeObject(databaseList),
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                success = false,
                message = string.Format("Databases not available at the moment due to {0}.      Please try reconnect to the database!", ex.Message),
                redirectUrl = Url.Action("Index", "DatabaseServerConnect")
            }, JsonRequestBehavior.AllowGet);
        }
    }

1 个答案:

答案 0 :(得分:1)

你发布的JSON看起来很有趣,因为它似乎是双重编码的。

但是查看服务器端代码清楚地表明这是您的问题:

databases = JsonConvert.SerializeObject(databaseList),

因此您对databases属性进行了双JSON编码,因为return Json已为您编码。

有两种方法可以解决这个问题:

  • 在服务器端摆脱双重编码,写着:

    return Json(new
        {
            success = true,
            databases = databaseList,
        }, JsonRequestBehavior.AllowGet);
    
  • 或者您需要在客户端显式JSON.parse response.databases

    var array = [];
    $.each(JSON.parse(response.databases), function (index, value) {
        array.push(new DatabaseViewModel(value));
    });
    self.databases(array);