【问题标题】:knockout.js viewmodel not binding in asp.net mvc controller for postknockout.js 视图模型未绑定在 asp.net mvc 控制器中以进行发布
【发布时间】:2017-08-20 01:42:22
【问题描述】:

我正在使用一个简单的示例将淘汰赛的视图模型发布到控制器。但它没有发生。控制器上的 dog 方法为空。

我做错了什么?

我的模特

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

我的控制器,其中 Dog 对象为空

[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);
            }
        });
    };
};

【问题讨论】:

  • 您是要从表单发布数据还是通过 ajax 发布?因为没有绑定到保存函数。
  • 通过 ajax 发布
  • 我认为我必须发送对象
  • 那么如何修改它以发送对象?

标签: asp.net-mvc knockout.js knockout-3.0


【解决方案1】:

尝试添加[FromBody]属性

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

并对 HTML 和 JavaScript 执行以下操作

<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>

【讨论】:

  • return XML Parsing Error: no root element found Location: moz-nullprincipal:{5403ac24-a9c4-4147-81c4-71d71452b173} Line Number 1, Column 1:
  • 发送这个运行 var data = { name: "age", age : 23 };
  • [FromBody] 为 observablearrays 绑定工作
猜你喜欢
  • 2018-04-22
  • 2016-03-14
  • 2012-11-13
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 2015-12-22
相关资源
最近更新 更多