2

I am trying to pass object from ajax to asp.net core

Here is asp code

[HttpPost]
public async Task<IActionResult> AddOrUpdate([FromForm] LSPost lsPost, List<IFormFile> files)
{
    return await Task.Run<IActionResult>(() =>
    {
        try
        {
            JsonResult t = ImageUpload(files).Result as JsonResult;
            string[] fullFilePathsReturned = t.Value as string[];

            lsPost.Media = fullFilePathsReturned[0];
            lsPost.Update();
            return Ok();
        }
        catch (Exception ex)
        {
            return StatusCode(500);
        }
    });
}

and here is ajax call

function UploadFile() {
    var lsPost = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(new LSPost()));

    lsPost.Title = $("#someText").val();

    console.log(lsPost);

    var fileData = new FormData();
    fileData.append("lsPost", lsPost);
    fileData.append("files", $("#someRandomID").get(0).files[0]);

    $.ajax({
        type: "POST",
        url: "/LSPostModel/AddOrUpdate",
        processData: false,
        contentType: false,
        data: fileData,
        success: function () {
        }
    });
}

parameter "files" is passed but "lsPost" is not. I tried adding / removing [FromForm] / [FromBody] tags. I tried matching first parameter of fileData.append with parameter name on back. I tried matching javascript object name with parameter name on back. Nothing is working....

Aleksa Ristic
  • 2,394
  • 3
  • 23
  • 54
  • Is the data actually being posted to the server? – Zze Dec 08 '20 at 01:13
  • You may need to swap `List files` to `IFormFile[] files` as sometimes C# can't deserialize to `List`. – Zze Dec 08 '20 at 01:16
  • Does this answer your question? [Upload files and JSON in ASP.NET Core Web API](https://stackoverflow.com/questions/41367602/upload-files-and-json-in-asp-net-core-web-api). The only extra change I would make is `fileData.append("lsPost", JSON.stringify(lsPost))` – Phil Dec 08 '20 at 01:26

1 Answers1

0

If you want to use ·formdata· to map multiple parameters at the same time. Please use simple types. For example, change the data in formdata to a basic type value. Change the parameter of action to string.

//ajax
fileData.append("lsPost", lsPost.Title);

//action
[HttpPost]
public async Task<IActionResult> AddOrUpdate([FromForm] string lsPost, List<IFormFile> files)
    {
     //...

enter image description here

The another solution, you can also put List<IFormFile> into LSPost. For example:

//ajax
fileData.append("Title", lsPost.Title);

//action
[HttpPost]
public async Task<IActionResult> AddOrUpdate([FromForm] LSPost lsPost)
    {
     //...

Model

public class LSPost
{
    public string Title { get; set; }
    public List<IFormFile> files { get; set; }
}

Note: An item of formdata cannot map the complex object type of the backend.

Karney.
  • 4,803
  • 2
  • 7
  • 11