1

動的に作成された各 DOM 要素に付加されたカスタム名属性を使用して、knockout.js で作成されたフォーム要素でサーバー側のモデル バインディングを実行したいと考えています。私は 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 を初めて使用しますが、ドキュメントを検索して、運のない助けを見つけました...助けてください...

4

1 に答える 1

2

$indexオブザーバブルであるため、次のようにアンラップする必要があります。$index()

<input type="text" 
   data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
<input type="text"
   data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
于 2012-11-26T06:51:00.277 に答える