敲除Js - 当使用Ajax初始化选择项时,无法设置默认项

时间:2015-08-18 18:14:21

标签: c# asp.net-mvc-5 knockout-3.0

My View is as below:
function event(EventType) {
    this.EventType = ko.observable(EventType)
 }

My View Model is as below:
function eventListViewModel(EventType) {
   self = this;
   self.Events = ko.observable(EventType)
    self.eventtypes= ko.observableArray([]);
    $.ajax({
        url: "../GetEventTypes/",
        type: "post",
        contentType: "application/json",
        async: true,
        cache: true,
        success: function (data) {
            var array = [];
            $.each(data, function (index, value) {
                array.push(value);
            });
            self.eventtypes(array);
        }
    });
 }

现在我已经初始化了我的视图模型,如下所示:

  $(function () {
            $.ajax({
                url: "@Url.Action("GetExistingEvents", new { Id = Model.Id})",
                type: "POST",
                data: {},
                success: function (data) {
                    //var events = ko.toJSON();
                    vm = new eventListViewModel(data);
                    ko.applyBindings(vm);
                }
         });
      });

以上Action将以json格式返回List of Below Event类:

public class Event
{
public int Id {get;set;}
public int Name {get;set;}
}

Public JsonResult GetExistingEvents()
{
List<Event> evnt = new List<Event>();
evnt.Add(new Event {Id : 1 , Name : "Test"});
return new Json(evnt );
}

现在我的下拉敲除绑定如下所示绑定EventTypes:

<div data-bind="foreach: Events ">
<select id="" class=" form-control col-md-8" data-bind="
          options: $root.eventtypes,optionsText: 'Name', optionsValue: 'Id',selectedOptions: $data.EventType,  optionsCaption: '--Please select an item --'"></select>
</div>

现在,我的问题是我无法设置所选的选项,PLease帮我解决了上述代码的错误?

0 个答案:

没有答案