通过jQuery将JSON数据发布到ASP .NET MVC 4控制器操作

我无法将复杂的JSON对象传递给MVC 4控制器操作。 由于JSON内容是可变的,所以我不希望MVC将JSON的各个属性/元素映射到action方法参数列表中的参数。 我只想在控制器操作中将数据作为单个JSONstring参数获取。

以下是我的操作方法的签名:

[HttpPost] [ValidateInput(false)] public string ConvertLogInfoToXml(string jsonOfLog) 

这里是我尝试从我的浏览器发布一些JSON数据:

  data = {prop: 1, myArray: [1, "two", 3]}; //'data' is much more complicated in my real application json = {jsonOfLog: data}; $.ajax({ type: 'POST', url: "Home/ConvertLogInfoToXml", data: JSON.stringify(json), success: function (returnPayload) { console && console.log ("request succeeded"); }, error: function (xhr, ajaxOptions, thrownError) { console && console.log ("request failed"); }, dataType: "xml", contentType: "application/json", processData: false, async: false }); 

当我在ConvertLogInfoToXML方法的开始点击中断点时,jsonOfLog为null。

如果我在JavaScript中更改了“json”variables,那么jsonOfLog属性就是一个简单的string,例如:

 json = { jsonOfLog: "simple string" }; 

那么当我在ConvertLogInfoToXML方法开始的断点时,jsonOfLog是string的值(例如“简单string”)。

我试着将action方法中的jsonOfLog参数的types改为objecttypes:

  [HttpPost] [ValidateInput(false)] public string ConvertLogInfoToXml(object jsonOfLog) 

现在,用原始的JavaScript代码(我传递一个更复杂的“数据”对象),jsonOfLog获取{object}的值。 但是debugging器不会在监视窗口中显示更多细节,我不知道可以使用什么方法来操作这个variables。

如何将JSON数据传递给MVC控制器,其中传递的数据是string化的复杂对象?

谢谢,Notre

问题是你的dataTypedata参数的格式。 我只是在一个沙箱中testing了这个,下面的作品:

C#

  [HttpPost] public string ConvertLogInfoToXml(string jsonOfLog) { return Convert.ToString(jsonOfLog); } 

JavaScript的

 <input type="button" onclick="test()"/> <script type="text/javascript"> function test() { data = { prop: 1, myArray: [1, "two", 3] }; //'data' is much more complicated in my real application var jsonOfLog = JSON.stringify(data); $.ajax({ type: 'POST', dataType: 'text', url: "Home/ConvertLogInfoToXml", data: "jsonOfLog=" + jsonOfLog, success: function (returnPayload) { console && console.log("request succeeded"); }, error: function (xhr, ajaxOptions, thrownError) { console && console.log("request failed"); }, processData: false, async: false }); } </script> 

要特别注意data ,发送文本时,需要发送一个与参数名称相匹配的variables。 这不是很漂亮,但它会让你co </s>不已格式​​化的string。

运行这个时,jsonOfLog在服务器function中看起来像这样:

  jsonOfLog "{\"prop\":1,\"myArray\":[1,\"two\",3]}" string 

HTTP POST标题:

 Key Value Request POST /Home/ConvertLogInfoToXml HTTP/1.1 Accept text/plain, */*; q=0.01 Content-Type application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With XMLHttpRequest Referer http://localhost:50189/ Accept-Language en-US Accept-Encoding gzip, deflate User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0) Host localhost:50189 Content-Length 42 DNT 1 Connection Keep-Alive Cache-Control no-cache Cookie EnableSSOUser=admin 

HTTP POST正文:

 jsonOfLog={"prop":1,"myArray":[1,"two",3]} 

响应标题:

 Key Value Cache-Control private Content-Type text/html; charset=utf-8 Date Fri, 28 Jun 2013 18:49:24 GMT Response HTTP/1.1 200 OK Server Microsoft-IIS/8.0 X-AspNet-Version 4.0.30319 X-AspNetMvc-Version 4.0 X-Powered-By ASP.NET X-SourceFiles =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?= 

答复机构:

 {"prop":1,"myArray":[1,"two",3]} 

我想你会find你的答案,如果你引用这个职位: 反序列化JSON到C#dynamic对象?

有很多方法可以实现你想要的东西。 System.Web.Helpers.Json方法(几个答案)似乎是最简单的。

VB.NET版本

好的,所以我花了几个小时寻找一个可行的方法来发布多个参数到一个MVC 4的WEB API,但是我发现的大部分是'GET'行动,或者只是平坦的没有工作。 但是,我终于得到了这个工作,我想我会分享我的解决scheme。

  1. 使用NuGet包来下载JSON-js json2Json.NET 。 安装NuGet软件包的步骤:

    (1)在Visual Studio中,转到网站 > pipe理NuGet软件包… 在这里输入图像描述

    (2)在search栏中inputjson(或者那个),findJSON-js json2Json.NET 。 双击它们将把软件包安装到当前项目中。 在这里输入图像描述

    (3)NuGet会自动将json文件放在~/Scripts/json2.min.js中的项目目录中。 findjson2.min.js文件并将其拖放到网站的头部。 注意 :有关安装.js(javascript)文件的说明,请阅读此解决scheme

  2. 创build一个包含所需参数的类对象。 您将使用它来访问API控制器中的参数。 示例代码:

     Public Class PostMessageObj Private _body As String Public Property body As String Get Return _body End Get Set(value As String) _body = value End Set End Property Private _id As String Public Property id As String Get Return _id End Get Set(value As String) _id = value End Set End Property End Class 
  3. 然后,我们设置我们将用于POST操作的MVC 4 Web API控制器。 在这里,我们将使用Json.NET来反序列化string对象的时候。 请记住使用适当的名称空间。 继续前面的例子,这是我的代码:

     Public Sub PostMessage(<FromBody()> ByVal newmessage As String) Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage) Dim body As String = t.body Dim i As String = t.id End Sub 
  4. 现在我们已经将我们的API控制器设置为接收string化的JSON对象,我们可以使用$ .ajax从客户端自由地调用POST操作。 继续前面的例子,这里是我的代码(正确replacelocalhost + rootpath):

     var url = 'http://<localhost+rootpath>/api/Offers/PostMessage'; var dataType = 'json' var data = 'nothn' var tempdata = { body: 'this is a new message...Ip sum lorem.', id: '1234' } var jsondata = JSON.stringify(tempdata) $.ajax({ type: "POST", url: url, data: { '': jsondata}, success: success(data), dataType: 'text' }); 

正如您所看到的,我们基本上是构buildJSON对象,将其转换为string,将其作为单个parameter passing,然后通过JSON.NET框架重新构build它。 我没有在我们的API控制器中包含返回值,所以我只是在success()函数中放置了一个任意的string值。


作者的笔记

这是在Visual Studio 2010中使用ASP.NET 4.0,WebForms,VB.NET和MVC 4 Web API控制器完成的。 对于将MVC 4 Web API与VS2010集成在一起时遇到困难的人,可以下载这个补丁来使之成为可能。 你可以从微软的下载中心下载

这里有一些额外的参考帮助(主要在C#中):

  • 使用jQuery来发布身体参数
  • 发送JSON对象到Web API
  • 当然托雷斯的回答是最后一块难题。

//在asp.net mvc中简单的json对象

 var model = {"Id": "xx", "Name":"Ravi"}; $.ajax({ url: 'test/[ControllerName]', type: "POST", data: model, success: function (res) { if (res != null) { alert("done."); } }, error: function (res) { } }); //model in c# public class MyModel { public string Id {get; set;} public string Name {get; set;} } //controller in asp.net mvc public ActionResult test(MyModel model) { //now data in your model } 

几个月前,我遇到了一个奇怪的情况,我也需要发送一些JSON格式的date回到我的控制器。 这就是我把头发拉出来后想到的:

我的课堂看起来像这样:

 public class NodeDate { public string nodedate { get; set; } } public class NodeList1 { public List<NodeDate> nodedatelist { get; set; } } 

和我的C#代码如下:

  public string getTradeContribs(string Id, string nodedates) { //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}"; // sample Json format System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer(); NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1)); string thisDate = ""; foreach (var date in nodes.nodedatelist) { // iterate through if needed... thisDate = date.nodedate; } } 

所以我能反序列化我的nodeDates Json对象参数在“节点”对象; 当然自然使用类“NodeList1”使其工作。

我希望这有助于…鲍勃

那么我的客户端(一个cshtml文件)正在使用DataTables显示一个网格(现在使用Infragistics控件,这是伟大的)。 一旦用户点击行,我捕获行事件和与该logging相关的date,以便返回到服务器,并进行额外的服务器端交易请求等。而不是 – 我没有把它的string化。 ..

DataTables def是以这种方式开始的(留下了很多东西),点击事件在下面的地方看到我的Json对象:

  oTablePf = $('#pftable').dataTable({ // INIT CODE "aaData": PfJsonData, 'aoColumnDefs': [ { "sTitle": "Pf Id", "aTargets": [0] }, { "sClass": "**td_nodedate**", "aTargets": [3] } ] }); $("#pftable").delegate("tbody tr", "click", function (event) { // ROW CLICK EVT!! var rownum = $(this).index(); var thisPfId = $(this).find('.td_pfid').text(); // Find Port Id and Node Date var thisDate = $(this).find('.td_nodedate').text(); //INIT JSON DATA var nodeDatesJson = { "nodedatelist":[] }; // omitting some code here... var dateArry = thisDate.split("/"); var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1]; nodeDatesJson.nodedatelist.push({ nodedate: nodeDate }); getTradeContribs(thisPfId, nodeDatesJson); // GET TRADE CONTRIBUTIONS });