MVC淘汰选择标签值赋值

时间:2017-01-24 17:59:54

标签: javascript c# jquery asp.net-mvc knockout.js

我正在尝试从ajax调用加载select标记。我可以加载select语句,但是当我尝试分配值时它会失败。谢谢你的帮助!

HTML代码

<select data-bind="value: state, options: allStates, optionsText: 'name', optionsValue: 'abbreviation', optionsCaption:'Please pick a state...'" class="form-control" id="state" name="state"></select>'

var cSource = function (data) {
    var self = this;'
    self.state = ko.observable(data.state);
    self.allStates = ko.observableArray([]);

// get the list of states from the server
$.getJSON('@Url.Action( "AllStates", "Home" )', function(myData) {
    // myDate is a list of states
    self.allStates(myData);
});

Not Assigned

var modelData = @Html.Raw( Json.Encode( Model ) );  // does not contain a list of states
    mySource = new cSource(modelData); 
    ko.applyBindings(mySource);

C#Object

public static List<cStates> usStates()
 {
        List<cStates> myStates = new List<cStates>();
        myStates.Add( new cStates() { abbreviation = "AL", name = "ALABAMA" } );
        myStates.Add( new cStates() { abbreviation = "AK", name = "ALASKA" } );
        ....
        return myStates;
 }

控制器

public ActionResult AllStates()
  {
        return Json( ChoiceProducts.States.BLL.cStates.usStates(), JsonRequestBehavior.AllowGet);
  }

如果我从javascript json对象加载状态就可以了。

var states = [{"name": "Alabama","abbreviation": "AL"},{"name": "Alaska",
    "abbreviation": "AK"},.....
self.state = ko.observable(data.state);
self.allStates = ko.observableArray(states);

Properly Assigned

2 个答案:

答案 0 :(得分:0)

您需要将knockout的ko.utils.arrayMap用于来自服务器的数据。在应用绑定之前,请执行以下操作:

var mappedState = ko.utils.arrayMap(stateObjectFromServer, function(item) {
    return new State(item.name, item.abbreviation);
});

这是一个很好的资源来帮助解决这个问题:

http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html

答案 1 :(得分:0)

控制器,我添加了

ViewBag.myStates = ChoiceProducts.States.BLL.cStates.usStates();

HTML,我添加了

self.allStates = ko.observableArray(@Html.Raw( Json.Encode( ViewBag.myStates ) ));

它有效。我没有必要以这种方式进行单独的ajax调用。