2017-08-15 57 views
0

如果我想更新模型,表面不會更新,但模型已經。Mvc dotnet核心淘汰賽模型不更新UI

保存方法後,模型更新,但不是圖形界面。

有誰知道我如何更新模型,以便視圖也可以進行更改。

查看:

var model = ko.mapping.fromJS(@Html.Raw(this.Model)); 

    var code = document.getElementById("editor-area"); 

    var editor = CodeMirror.fromTextArea(code, { 
       lineNumbers: true, 
       matchBrackets: true, 
       mode: "text/x-csrc", 
       lineWrapping: true, 
       theme: 'the-matrix'}); 

      model.save = function() { 
       model.CurrentSnippet.Code(editor.getValue()); 
       var url = "/Snippet/Save"; 

       $.ajax({ 
        url: url, 
        method: "POST", 
        data: { viewModel: ko.toJS(model.CurrentSnippet)}, 
        }).done(function(response) { 
         model = ko.mapping.fromJS(ko.mapping.fromJSON(response)); 
        }).fail(function(jqXHR, textStatus) { 
        alert("fail: " + textStatus); 
       }); 
      } 

    var bindContainer = document.getElementById("editor"); 
    ko.applyBindings(model, bindContainer); 

控制器:

public IActionResult Save(ViewModelSnippet viewModel) 
    { 
     var model = Mapper.MappeViewModelSnippetZuSnippet(viewModel); 
     _snippetRepository.Save(model); 
     var returnModel = JsonConvert.SerializeObject(new ViewModelSnippets { Selection = Guid.NewGuid(), Snippets = Mapper.MappeSnippetsZuViewModelSnippets(_snippetRepository.GibAlleSnippets()) , CurrentSnippet = viewModel}); 
     return Json(returnModel); 
    } 

Chrome檢查/控制檯:

型號befor節約:節約

{CurrentSnippet: {…}, __ko_mapping__: {…}, Selection: ƒ, Snippets: ƒ, save: ƒ, …} 
CurrentSnippet 
: 
{SnippetId: ƒ, Name: ƒ, Description: ƒ, Code: ƒ, Modified: ƒ} 
Selection 
: 
ƒ c() 
Snippets 
: 
ƒ c() 
clear 
: 
ƒ() 
deploy 
: 
ƒ() 
load 
: 
ƒ() 
save 
: 
ƒ() 
snippetClick 
: 
ƒ (data) 
__ko_mapping__ 
: 
{ignore: Array(0), include: Array(1), copy: Array(0), observe: Array(0), mappedProperties: {…}, …} 
__proto__ 
: 
Object 

後:

{CurrentSnippet: {…}, __ko_mapping__: {…}, Selection: ƒ, Snippets: ƒ} 
CurrentSnippet 
: 
{SnippetId: ƒ, Name: ƒ, Description: ƒ, Code: ƒ, Modified: ƒ} 
Selection 
: 
ƒ c() 
Snippets 
: 
ƒ c() 
__ko_mapping__ 
: 
{mappedProperties: {…}, ignore: ƒ, include: ƒ, copy: ƒ, observe: ƒ, …} 
__proto__ 
: 
Object 

回答

2

也許你需要在ajax.done更新視圖模型,而不是娛樂:

  }).done(function(response) { 
       // Created here a model instance is not bound to the UI 
       model = ko.mapping.fromJS(ko.mapping.fromJSON(response)); 
      }).fail(function(jqXHR, textStatus) { 

你可以做到這一點在映射plugin documentation喜歡描述:

var data = { 
    name: 'Scot', 
    children: [ 
     { id : 1, name : 'Alicw' } 
    ] 
} 

你可以將其映射到視圖模型沒有任何問題:

var viewModel = ko.mapping.fromJS(data); 

現在,讓我們說,數據更新是沒有任何錯別字:

var data = { 
    name: 'Scott', 
    children: [ 
     { id : 1, name : 'Alice' } 
    ] 
} 

兩件事情都發生在這裏:名稱由蘇格蘭人改爲斯科特和 兒童[0]。名稱從Alicw改變給打字錯誤的愛麗絲。

ko.mapping.fromJS(data, viewModel); 
+0

謝謝它的工作原理:您 可以根據這個新的數據更新視圖模型 –