Knockout Js Dropdown未加载来自Web APi Service的值

时间:2013-01-09 14:28:23

标签: javascript asp.net-mvc-4 knockout.js asp.net-web-api html.dropdownlistfor

Knockout Js Dropdown未加载来自WebAPi服务的值

代码如下,请帮助我。

这是淘汰js要求下拉

<select data-bind="options: menus, optionsText: 'text', optionsValue: 'pk_smartMenuID',  optionsCaption: 'Choose...'"></select>

Web APi致电

    // GET api/SmartMenu
    public IEnumerable<SmartMenu> GetSmartMenus()
    {
        var smartmenus = _db.SmartMenus.Include(s => s.ParentSmartMenu);
        return smartmenus.AsEnumerable();
    }

这是联系web api服务器调用的视图模型(脚本)

@section Scripts { 
@Scripts.Render("~/bundles/jqueryval") 
@Scripts.Render("~/bundles/knockout") 

<script type="text/javascript">
    function MenuViewModel() {
        var self = this;
        var baseUri = '@ViewBag.ApiUrl';
        self.menus = ko.observableArray([]);
        self.selectedMenu = ko.observable();

        self.addMenu = function(formElement) {
          // If valid, post the serialized form data to the web api 
          $(formElement).validate();
          if ($(formElement).valid()) {
            $.post(baseUri, $(formElement).serialize(), null, "json")
            .done(function(o) { self.menus.push(o); });
          }
        };

        $.getJSON(baseUri, self.menus);
      }

      $(document).ready(function() {
        ko.applyBindings(new MenuViewModel());
      });
</script> 
} 

1 个答案:

答案 0 :(得分:0)

由于json数据在Linkedlist中需要迭代, 我在http://knockoutjs.com/documentation/json-data.html

中得到了答案