[英]How to: (a) send JSON data from the browser to the controller; and (b) send the transformed data to SQL Server within ASP.NET MVC?
I have a form which includes a variety of <input>
elements and makes use of 1-to-n tabulator tables for data input.我有一个表单,其中包含各种<input>
元素,并使用 1 对 n 制表符表进行数据输入。 I have managed to successfully assemble data from these elements into a JSON string.我已经成功地将来自这些元素的数据组装成一个 JSON 字符串。 I am now attempting to complete the following two steps:我现在正在尝试完成以下两个步骤:
My client-side script to POST the JSON object is as follows:我发布 JSON object 的客户端脚本如下:
var myJson = "the data from the form elements is programmatically inserted into the JSON string";
// use parseJSON() to test the syntax
try {
var obj = jQuery.parseJSON(myJson);
}
catch(error) {
console.log(error);
}
$.ajax({
type: "POST",
url: "/Dailies/UploadJson/",
dataType: 'json',
data: JSON.stringify(myJson),
contentType: 'application/json',
crossDomain: true,
cache: false,
success: function(data) { console.log(data); }
});
The method called within my ASP.NET MVC controller appears as follows:在我的 ASP.NET MVC controller 中调用的方法如下所示:
[HttpPost]
public IActionResult UploadJson(Object jsonFile)
{
// insert data into SQL Server table
}
Note: I have already created the appropriate domain model within my ASP.NET MVC app and have also added a DbSet
reference to the DbContext
model. I have verified my ability to insert rows into the SQL Server table using mock data.注意:我已经在我的 ASP.NET MVC 应用程序中创建了适当的域 model,并且还添加了对DbContext
model 的DbSet
引用。我已经验证了我使用模拟数据将行插入到 SQL 服务器表中的能力。
When I place a breakpoint inside the UploadJson()
method, I find that the jsonFile object is null.当我在UploadJson()
方法中放置一个断点时,我发现 jsonFile object 是 null。
My quandry at this point is two-fold:在这一点上,我的困惑有两个:
Any assistance is greatly appreciated.非常感谢任何帮助。
Although there are plenty of questions related to this, the answers to those typically refer to binding to a model instead of just the json string.尽管有很多与此相关的问题,但这些问题的答案通常是指绑定到 model 而不仅仅是 json 字符串。 But those will also help you.但这些也会帮助你。
It looks like there are two things:看起来有两件事:
string
instead of an object.我会更改 controller 以接收string
而不是 object。jsonFile
.您需要更新传递给 controller 的 json 数据,以匹配 controller 的参数名称。因此,在这种情况下,controller 将接收名为jsonFile
的参数。 So in the $.ajax
method you'll want update the data
to something like:因此,在$.ajax
方法中,您需要将data
更新为如下内容:data: { jsonFile: JSON.stringify(myJson) }
UPDATE:更新:
application/json
删除application/json
的 Content-Type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.