【问题标题】:ASP.NET MVC model binding with knockout.jsASP.NET MVC 模型与 knockout.js 的绑定
【发布时间】:2012-11-13 15:17:17
【问题描述】:

我想对使用 knockout.js 创建的表单元素进行一些服务器端模型绑定,使用附加到每个动态创建的 DOM 元素的一些自定义名称属性。我知道我可以使用 AJAX,但本机 HTML 表单帖子现在对我来说效果更好。 js文件长这样:

function MyModel(){ 
   var self = this;
   var count = 0;
   var insertItem = function(eleToInsertAfter){
       var index = self.items.indexOf(eleToInsertAfter),
           notFound = -1;

       var item = {
           type: '',
           description: ''
       };

       if(index == notFound){
           self.items.push(item); // there are no items yet, just push this item
       } else {
           self.items.spilce(++index, 0, item); // insert after the 'eleToInsertAfter' index
       }
       ++count;
   }

   self.title = ko.observable('');
   self.items = ko.observableArray([]);

   self.insert = function(eleToInsertAfter){
       insertItem(eleToInsertAfter);
   }

   // insert the first item
   self.insert({
           type: '',
           description: ''
       });
}
   ko.applyBindings(new MyModel());

html 标记如下所示:

<form method="post" action="/controller/action/">
     <input type="text" data-bind="value: title" />
     <ol data-bind="foreach: items">
          <li> 
               <!--I'd like to achieve this effect *name="[0].type"* and *name="[0].description"*, and so on -->
               <input type="text" data-bind="value: type, *attr: {name = '['+$index+'].type'}*" />
               <input type="text" data-bind="value: description, *attr: {name = '['+$index+'].description'}*" /><br />
               <button data-bind="click: $root.insert">Add Item</button>
          </li>
     </ol>
     <input type="submit" value="Submit" />
</form>

如果我能达到上述效果,那么 MVC 控制器动作可能如下所示:

public ActionResult action(MyModelCS model){
    // do something

    return View();
}

MyModelCS 看起来像这样:

public class MyModelCS {
    public string title { get; set; }
    public string[] type { get; set; }
    public string[] description { get; set; }
}

我只使用 jQuery 实现了一个与此类似的版本,但现在我需要使用 Knockout.js 来做一个类似的版本。我是 Knockout 的新手,但我搜索了文档以找到一些帮助,但没有任何运气...请帮助...

【问题讨论】:

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


    【解决方案1】:

    $indexan observable 所以你需要解包:$index()

    <input type="text" 
       data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
    <input type="text"
       data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
    

    【讨论】:

      猜你喜欢
      • 2014-01-19
      • 2018-12-10
      • 2015-07-17
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多