2017-03-27 6 views
2

간단한 예제를 사용하여 녹아웃의 viewmodel을 컨트롤러에 게시합니다. 그러나 그것은 일어나지 않습니다. 컨트롤러의 dog 메서드가 null이됩니다.knockout.js viewmodel은 asp.net에 바인딩되지 않았습니다 게시물에 대한 mvc 컨트롤러

내가 뭘 잘못하고 있니?

내 모델

public class Dog 
{ 
    public string name { get; set; } 
    public int age { get; set; } 
} 

내 컨트롤러가있는 개 오브젝트가 null

[HttpPost] 
public ActionResult Save(Dog dog) 
{ 
    return Json(new { Status = string.Format("Success, saved {0} with age: {1}", dog.name, dog.age) }); 
} 

보기

<form method="POST" data-bind="submit: save"> 
    <div>Name:</div> 
    <div><input type="text" data-bind="value: name" /></div> 

    <div>Age:</div> 
    <div><input type="text" data-bind="value: age" /></div> 

    <div><input type="submit" value="Save" /></div> 
</form> 


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

    //self.isValid = ko.computed(function() { 
    // return self.name().length > 0; 
    //}); 

    self.save = function() { 
     $.ajax({ 
      url: "Home/Save", 
      type: "post", 
      contentType: "application/json", 
      data: ko.mapping.toJSON(self), 
      success: function (response) { 
       alert(response.Status); 
      } 
     }); 
    }; 
}; 
+0

폼 또는 아약스 게시물을 통해 데이터를 게시하려고합니까? 저장 기능에 바인딩이 없기 때문입니다. – muhihsan

+1

통해 아약스 게시물 – maztt

+0

나는 개체를 보낼 수 있도록 – maztt

답변

1

을 받고 봅니다 추가 [FromBody] 속성

하여 HTML과 자바 스크립트에 다음
[HttpPost] 
public ActionResult Save([FromBody]Dog dog) 
{ 
    return Json(new { Status = string.Format("Success, saved {0} with age: {1}", dog.name, dog.age) }); 
} 

그리고 할 는

<div>Name:</div> 
<div><input type="text" data-bind="value: name" /></div> 

<div>Age:</div> 
<div><input type="text" data-bind="value: age" /></div> 

<div><button data-bind="click: save">Save</button></div> 

<script> 
    var ViewModel = function() { 
    var self = this; 
    self.name = ko.observable(); 
    self.age = ko.observable(); 

    self.save = function() { 
     var jsonData = {'name': self.name(), 'age': self.age()}; 
     $.ajax({ 
      url: "http://localhost:8000/home/saves", 
      type: "post", 
      contentType: "application/json", 
      data: jsonData, 
      success: function (response) { 
       alert(response.Status); 
      } 
     }); 
    }; 
    }; 

    ko.applyBindings(new ViewModel()); 
</script> 
+0

반환 XML 구문 분석 오류 : 루트 요소를 찾을 수 없음 위치 : moz-nullprincipal : {5403ac24-a9c4-4147-81c4-71d71452b173} 행 번호 1, 열 1 : – maztt

+0

실행하면 var data = { name : "age", 연령 : 23 }; – maztt

+0

결과를 수정했습니다. 이것은 나와 함께 일하고있다 – muhihsan