2013-07-19 25 views
1

我想使用淘汰賽的視圖上傳文件和顯示列表。爲此,我使用jquery.form.js以便使用ajax上傳它們。我已經改變了使用淘汰賽,我的視圖模型看起來像這樣通過AJAX上傳文件時更新淘汰賽viewmodel

var ViewModel = function (groups) { 
    var self = this; 

    self.groups = ko.observableArray(ko.utils.arrayMap(groups, function (group) { 
     return { 
      planName: ko.observable(group.Key), 
      documentList: ko.observableArray(ko.utils.arrayMap(group.Values, function (value) { 
       return { 
        document: ko.observable(new Document(value)) 
       }; 
      })) 
     }; 
    })); 

    var options = { 
     dataType: 'json', 
     success: submissionSuccess 
    }; 

    self.add = function() { 
     $('#addForm').ajaxSubmit(options); 
     return false; 
    }; 

    function submissionSuccess(result) { 
     alert('success'); 
    } 
}; 

有一個Document功能來做映射。從控制器接收Json數據時,我卡住了。結果是正確的,這是我在第一次加載時收到的格式相同的對象列表,但我不知道如何「刷新」視圖模型以使用此新列表。

不知道使用ko映射插件會使它更容易,因爲我從來沒有使用它,甚至不知道它是否適用於此。

控制器法中,是相關的,是這樣的(如果其他neede讓我知道althoug將無法訪問的代碼在接下來的幾個小時)

[HttpPost] 
public ActionResult AddDocument(AddDocumentViewModel viewModel) 
{ 
    var partyId = Utils.GetSessionPartyId(); 

    if (viewModel.File.ContentLength > Utils.GetKBMaxFileSize * 1024) 
     ModelState.AddModelError("File", String.Format("The file exceeds the limit of {0} KB", Utils.GetKBMaxFileSize)); 

    if (ModelState.IsValid) 
    { 
     _documentsManager.AddDocument(viewModel, partyId); 

     if (Request.IsAjaxRequest()) 
     { 
      var vm = _displayBuilder.Build(partyId); 
      return Json(vm.Documents); 
     } 

     return RedirectToAction("Index"); 
    } 

    var newViewModel = _createBuilder.Rebuild(viewModel, partyId); 
    return PartialView("_AddDocument", newViewModel); 

} 

感謝

編輯我想出了這個代碼,似乎工作(該功能視圖模型裏面一個

function submissionSuccess(result) { 
    self.groups(ko.utils.arrayMap(result, function (group) { 
     return { 
      planName: ko.observable(group.Key), 
      documentList: ko.utils.arrayMap(group.Values, function (value) { 
       return { 
        document: new Document(value) 
       }; 
      }) 
     }; 
    })); 
}; 
+0

所以基本上你需要更換可觀察組的內容? –

+0

是的。理想情況下,我想替換一個(或者在不存在的情況下添加它),但它可以替代所有這些文件 – mitomed

回答

1

你確定documentListdocument NE編輯是自己觀察?

要更新列表,您可以按照常規陣列的方式推送它。 你可以嘗試這樣的:

function submissionSuccess(result) { 
    self.groups.removeAll(); 

    $.each(result, function(index, value) { 
    var documentList = []; 

    $.each(value.Values, function(index, value) { 
     documentList.push(new Document(value)); 
    }); 

    var group = { 
     planName:value.Key, 
     documentList: documentList 
    }; 

    self.groups.push(group); 
    }); 
}; 
+0

謝謝。當再次訪問代碼時,我會放棄它,但看起來不錯。我列出了可觀察的名單,因爲我正在考慮能夠推出一份文件,但可能並不需要你說的。儘管這個文檔對於在同一視圖中進行編輯可能很有用。 – mitomed

+0

對不起。對於不將該解決方案標記爲核心解決方案抱歉,因爲我無法在我的代碼中運行它(正在失去進一步的綁定)。雖然這可能是因爲我的問題缺乏背景,所以我對它讚不絕口。無論如何,我編輯和添加我最終使用的。 – mitomed