lovida5233
lovida5233

Reputation: 17

Ajax FormData return null

I created a form. I am sending the data in this form as JSON.

If I just submit the formData (I also change the controller to [FromBody] Image request) and set the contentType and processData to false, the formData is not null.

I think "document" returns null because I am sending the data as JSON. How can I solve this issue I'm stuck in this issue.

Ajax Request

   let myProfile = {
        id: 0,
        title: "",
        text: "",
        document: File,
    };
    
        myProfile.title = "Lorem ipsum"; 
        myProfile.text = "Lorem ipsum"; 

        var formData = new FormData();
        formData.append('file', $('#file').get(0).files[0]);
        formData.append('fileName', $("#fileName").val());

        var myFile = formData.get('file');
        myProfile.document = myFile;

    $.ajax({
       url: `/admin/myprofile`,
       type: "POST",
       data: JSON.stringify(myProfile),
       contentType: "application/json",
       dataType: 'json',
       success: ....

Cshtml

    <div class="form-group">
        <input type="file" name="document" asp-for="document" id="file" />
    </div>

Controller

    [HttpPost("myprofile")]
    public IActionResult MyProfile([FromBody] MyProfileDTO request)
    {
        return ...
    }

Class

    public class Image
    {
      public IFormFile file { get; set; }
      public string fileName { get; set; }
    }

    public class MyProfileDTO 
    {
        public string Title { get; set; }
        public string Text { get; set; }
        public Image Document{ get; set; }
    }

Upvotes: 0

Views: 1232

Answers (1)

KHYT
KHYT

Reputation: 1

Ajax Request

   let myProfile = {
        id: 0,
        title: "",
        text: "",
        document: File,
    };
    
        myProfile.title = "Lorem ipsum"; 
        myProfile.text = "Lorem ipsum"; 

        var formData = new FormData();
        formData.append('file', $('#file').get(0).files[0]);
        formData.append('title', myProfile.title);
        formData.append('text', myProfile.text);


    $.ajax({
       url: `/admin/myprofile`,
       type: "POST",
       data: formData ,
       contentType: "application/json",
       success: ....

Controller

    [HttpPost("myprofile")]
    public IActionResult MyProfile([FromBody] MyProfileDTO request, IFormFile file)
    {
        return ...
    }

Class

    

    public class MyProfileDTO 
    {
        public string Title { get; set; }
        public string Text { get; set; }
    }

Upvotes: 0

Related Questions