2013-03-20 80 views
0

我有一个MVC控制器的以下功能如何通过knockoutjs视图模型为MVC控制器

public class XyzController:Controller 
{ 
    public ActionResult Index(){...} 
    [HttpPost] 
    public bool Save(string jsondata) 
    { 

     //parse json data to insert into the database 
    } 
} 

我想这个视图模型传递到保存功能

var myObj = function (id) { 
    var self = this; 
    self.myId = id;  
    self.parameters = ko.observableArray();  
} 

var ViewModel = function() { 
    var self = this;  
    self.myObjList = ko.observableArray(); 
    self.sendItems = function() { 
      $.ajax({ 
        type: "POST", 
        url: '/Xyz/Save', 
        data: ko.toJSON(self), 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (response) { 
          alert(response); 
        }, 
        error: function (request, status, error) { 
          alert(request.statusText); 
        } 
      }); 
    } 
} 

var vm = new ViewModel() 
ko.applyBindings(vm); 

我做得到如果我将数据作为JSON.stringify({jsondata:ko.toJSON(self)})传递数据,但是如何将其转换为对象以便我可以迭代myObjList和参数?

+3

只要有操作方法接受任何的对象类型的对象。让模型联编程序完成这项工作。 – 2013-03-20 15:25:49

+0

完全同意Andrew的观点:你绕开了MVC的天生能力之一。更改签名以接收目标对象类型,并让MVC为您执行映射。 – 2013-03-21 13:53:56

回答

1

首先试着改变你的模型是这样的: -

[JsonObject(MemberSerialization.OptIn)] 
    public class Test 
    { 

     [JsonProperty("myId")] 
     public string Id { get; set; } 

     [JsonProperty("parameters")] 
     public List<string> Parameters { get; set; }//List<string> or whatever it takes int of string 

    } 

,如果它不工作,请把你的Ajax请求数据......否则....

我遵循的做法是这样的: -

MODEL: -

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Newtonsoft.Json; 

namespace MvcApplication4.Models 
{ 
    [JsonObject(MemberSerialization.OptIn)] 
    public class Test 
    { 

     [JsonProperty("id")] 
     public string Id { get; set; } 

     [JsonProperty("name")] 
     public string Name { get; set; } 

    } 
} 

控制器

 // 
     // POST: /Testing/ 
     [HttpPost] 
     public void Post(MvcApplication4.Models.Test request) 
     { 

      try 
      { 
       //DO YOUR STUFF 
      } 
      catch (Exception ex) 
      { 
       throw (ex); 
      } 

     } 

AJAX调用: -

var json = {}; 
json = data.id; 
json = data.name; 

$.ajax({ 
      type: "POST", 
      url: ""//Your URL, 
      dataType: "json", 
      contentType: 'application/json; charset=utf-8', 
      data: ko.toJSON(json) 
     }).done(function (data) { 

     }).fail(function (request, error) { 

     }); 

或者使你的AJAX调用像

$.ajax({ 
       type: "POST", 
       url: ""//Your URL, 
       dataType: "json", 
       contentType: 'application/json; charset=utf-8', 
       data: ko.toJSON({ id: value1, name: value2 }),//Get value1 and value2 from you ko varables 
      }).done(function (data) { 

      }).fail(function (request, error) { 

      });