来自MVC的Knockout映射

时间:2016-05-03 12:36:24

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

我使用ko.mapping实用程序将我的mvc模型绑定到knockoutjs。 我的mvc模型是这个

  public class Person
  {
    public string Name { get; set; }
    public string Surname { get; set; }
    public Achievement[] achievements { get; set; }
  }

  public class Achievement
  {
     public string Title { get; set; }
     public int Score { get; set; }
  }


  public ActionResult Index()
  {
     Person person = new Person
     {
        Name = "Name",
        Surname = "Surname",

        achievements = new Achievement[]
        {
           new Achievement { Title="Ach 1", Score=10 },
           new Achievement { Title="Ach 2", Score=11 },
           new Achievement { Title="Ach 3", Score=12 },
        }
     };
     return View(person);
  }

我希望我的javascript模型在Person和Achievement对象中包含一些额外的属性,所以我使用knockout mapping plugin并在javascript中只编写新属性(Person.fullName和Achievement.Message)。

@{
    string theData = new JavaScriptSerializer().Serialize(Model);
 }
  <div>
    <div><label>Name </label> <span data-bind="text:Name"></span></div>
    <div> <label>Surname </label> <span data-bind="text:Surname"></span> </div>
    <div> <label>Full Name </label> <span data-bind="text:fullName"></span></div>

    <ul data-bind="foreach:achievements">
        <li>
            <span data-bind="value:Title" />
            <span data-bind="text:Score"></span>
            <span data-bind="text:Message"></span>
        </li>
    </ul>
</div>
<script type="text/javascript">
    personViewModel = function (data) {
        var self = this;
        ko.mapping.fromJS(data, {}, self);  
        self.fullName = ko.computed(function () {
            return self.Name() + "   " + self.Surname();
        });
    }

    achievement = function (data) {
        var self = this;
        ko.mapping.fromJS(data, {}, self);

        self.Message = ko.computed(function () {
            return self.Title() + "  " + self.Score();
        });
    }
    ko.applyBindings(new personViewModel(@Html.Raw(theData)));
</script>

问题是成就类根本没有映射。什么是从MVC控制器加载数据的正确方法,而无需在c#和javascript中编写两次模型。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

var custMap = {};

custMap['achievements'] = {
 create: function(data) {
  var result = [];
  for(var i = 0; i < data.length; i++){
   result.push(new achievement(data[i]);
  }
  return new ko.observableArray(result);
 }
}

并绘制地图:

ko.mapping.fromJS(data, custMap, self);