通过Post Ajax方法传递包含对象的嵌套对象列表给Web API。

huangapple go评论102阅读模式
英文:

Passing a nested list of objects with objects in post ajax method for web api

问题

以下是翻译好的部分:

I am stuck in situation where I have nested list of objects inside objects. I am stuck and can't move any further.
(我陷入了一个情况,其中我在对象内部有嵌套的对象列表。我卡住了,无法继续前进。)

Working fine without passing oNestedClass.
(不传递 oNestedClass 时运行正常。)

And I'm having trouble passing a list of objects via JSON to Web Api.
(而且我在通过 JSON 将对象列表传递到 Web Api 中遇到了问题。)

The controller method:
(控制器方法:)

[HttpPost("SaveDocuments")]
public IActionResult SaveDocuments(Documenttest saveDocs)
{
var docTypeList = docContext.SaveDocuments(saveDocs);
return Ok(docTypeList);
}

Class:
(类:)

public class Documenttest
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Gender { get; set; }
public List? oNestedClass { get; set; } = new();
}

public class NestedClass
{
public string? StdType { get; set; }
public IFormFile? StdFile { get; set; }
}

Calling from .aspx page:
(从 .aspx 页面调用:)

$("#postform").submit(function (e) {
var apiurl = "https://localhost:7168/api/NestClass/SaveDocuments?";
var fileUpload = $(".uplFile");

var stdDetails = [];

for (var i = 0; i < fileUpload.length; i++) {
    var files = fileUpload[i];
    
    if (files.files.length > 0) {
        debugger
        stdDetails.push({ "StdType ": i, "StdFile ": files.files[i] });
    }
}

var data = {
    "FirstName": $("#txtFirstName").val(),
    "LastName": $("#txtLastName").val(),
    "Gender": $("#txtGender").val(),
    "oNestedClass": JSON.stringify(stdDetails)
}

$.ajax({
    type: 'POST',
    url: apiurl,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (d) {
        alert("Saved Successfully");
    },
    error: function () {
        alert("Error please try again");
    }
});

e.preventDefault();

});

英文:

I am stuck in situation where I have nested list of objects inside objects. I am stuck and can't move any further.

Working fine without passing oNestedClass.

And I'm having trouble passing a list of objects via JSON to Web Api.

The controller method:

[HttpPost(&quot;SaveDocuments&quot;)]
public IActionResult SaveDocuments(Documenttest saveDocs)
{
    var docTypeList = docContext.SaveDocuments(saveDocs);
    return Ok(docTypeList);
}

Class:

public class Documenttest
{
    public int Id { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? Gender { get; set; }
    public List&lt;NestedClass&gt;? oNestedClass { get; set; } = new();
}

public class NestedClass
{
    public string? StdType { get; set; }
    public IFormFile? StdFile { get; set; }
}

Calling from .aspx page:

$(&quot;#postform&quot;).submit(function (e) {
var apiurl = &quot;https://localhost:7168/api/NestClass/SaveDocuments?&quot;;
var fileUpload = $(&quot;.uplFile&quot;);

var stdDetails = [];

for (var i = 0; i &lt; fileUpload.length; i++) {
	var files = fileUpload[i];
	
	if (files.files.length &gt; 0) {
		debugger
		stdDetails.push({ &quot;StdType &quot;: i, &quot;StdFile &quot;: files.files[i] });
	}
}

var data = {
	&quot;FirstName&quot;: $(&quot;#txtFirstName&quot;).val(),
	&quot;LastName&quot;: $(&quot;#txtLastName&quot;).val(),
	&quot;Gender&quot;: $(&quot;#txtGender&quot;).val(),
	&quot;oNestedClass&quot;: JSON.stringify(stdDetails)
}

$.ajax({
	type: &#39;POST&#39;,
	url: apiurl,
	data: JSON.stringify(data),
	contentType: &quot;application/json; charset=utf-8&quot;,
	dataType: &#39;json&#39;,
	success: function (d) {
		alert(&quot;Saved Successfully&quot;);
	},
	error: function () {
		alert(&quot;Error please try again&quot;);
	}
});

e.preventDefault();});

答案1

得分: 1

尝试使用 formdata 来传递文件。注意,我们传递的数据是通过名称属性绑定的,比如:saveDocs.oNestedClass[&quot; + i + &quot;].StdFile,以保持与 API 操作参数 saveDocs 一致。

我有一个工作示例如下,您可以参考它:

  1. 将您的代码更改为:
$(&quot;#postform&quot;).submit(function (e) {
    var apiurl = &quot;https://localhost:7019/api/NestClass/SaveDocuments&quot;;
    var fileUpload = $(&quot;.uplFile&quot);        
    var formData = new FormData();
    for (var i = 0; i &lt; fileUpload.length; i++) {
        var files = fileUpload[i];          
        if (files.files.length &gt; 0) {
            debugger
            formData.append(&quot;saveDocs.oNestedClass[&quot; + i + &quot;].StdFile&quot;, files.files[i]);
            formData.append(&quot;saveDocs.oNestedClass[&quot; + i + &quot;].StdType&quot;, i);                                                         
        }         
    }
    formData.append(&quot;saveDocs.FirstName&quot;, $(&quot;#txtFirstName&quot;).val());
    formData.append(&quot;saveDocs.LastName&quot;, $(&quot;#txtLastName&quot;).val());
    formData.append(&quot;saveDocs.Gender&quot;, $(&quot;#txtGender&quot;).val());
    $.ajax({
        type: &#39;POST&#39;,
        url: apiurl,         
        data: formData,
        contentType: false,
        processData: false,
        success: function (d) {
            alert(&quot;Saved Successfully&quot;);
        },
        error: function () {
            alert(&quot;Error please try again&quot;);
        }
    });
    e.preventDefault();      
});
  1. 添加 [FromForm] 以接收 formdata
[HttpPost(&quot;SaveDocuments&quot;)]
public IActionResult SaveDocuments([FromForm]Documenttest saveDocs)
{
    var docTypeList = docContext.SaveDocuments(saveDocs);
    return Ok(docTypeList);
}

结果:

通过Post Ajax方法传递包含对象的嵌套对象列表给Web API。

英文:

Try to use formdata to pass the file. Note we pass the data binded by name attribute, such us: saveDocs.oNestedClass[&quot; + i + &quot;].StdFile , to keep same as the api action parameter saveDocs.

I have a work demo like below, you can refer to it:

1.change your code like :

$(&quot;#postform&quot;).submit(function (e) {
var apiurl = &quot;https://localhost:7019/api/NestClass/SaveDocuments&quot;;
var fileUpload = $(&quot;.uplFile&quot;);        
var formData = new FormData();
for (var i = 0; i &lt; fileUpload.length; i++) {
var files = fileUpload[i];          
if (files.files.length &gt; 0) {
debugger
formData.append(&quot;saveDocs.oNestedClass[&quot; + i + &quot;].StdFile&quot;, files.files[i]);
formData.append(&quot;saveDocs.oNestedClass[&quot; + i + &quot;].StdType&quot;, i);                                                         
}         
}
formData.append(&quot;saveDocs.FirstName&quot;, $(&quot;#txtFirstName&quot;).val());
formData.append(&quot;saveDocs.LastName&quot;, $(&quot;#txtLastName&quot;).val());
formData.append(&quot;saveDocs.Gender&quot;, $(&quot;#txtGender&quot;).val());
$.ajax({
type: &#39;POST&#39;,
url: apiurl,         
data: formData,
contentType: false,
processData: false,
success: function (d) {
alert(&quot;Saved Successfully&quot;);
},
error: function () {
alert(&quot;Error please try again&quot;);
}
});
e.preventDefault();      
});

2.add [FromForm] to recieve formdata

[HttpPost(&quot;SaveDocuments&quot;)]
public IActionResult SaveDocuments([FromForm]Documenttest saveDocs)
{
var docTypeList = docContext.SaveDocuments(saveDocs);
return Ok(docTypeList);
}

result:

通过Post Ajax方法传递包含对象的嵌套对象列表给Web API。

huangapple
  • 本文由 发表于 2023年3月10日 01:27:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75688070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定