admin管理员组

文章数量:1129200

I am trying to submit form data through an Ajax call and not passing FormData, but instead passing a custom object in the Ajax call.

This is my ajax call:

function submitData() {
    let isValid = true;
    var bankViewModel = {};
    
    {
        bankViewModel = {
            Name: $("#name").val(),
            Website: $("#website").val(),
            Logo: $("input#logo")[0].files[0],
      //      Logo: null,
            StartDate: $("#startDate").val(),
            Stars: $("#stars").val(),
            Branches: []
        };

        // branches
        $("#branchTable tbody tr").each(function (index, row) {
            const branch = {
                Name: $(row).find(".branch-name").val(),
                Email: $(row).find(".branch-email").val(),
                Status: $(row).find(".branch-status").is(":checked"),
                Photo: $(row).find(".branch-photo")[0].files[0]
            //    Photo: null
            };
        bankViewModel.Branches.push(branch);
        });

        console.log("++++++++BANK+++++++++");
    console.log(bankViewModel);
        console.log("+++++++++++++++++");
    }

    if (isValid) {
        $.ajax({
            type: "POST",
            url: "@Url.Action("Create", "BanksV62")",
     //       data: form,
        data: {bankViewModel},
       //     contentType: ,
            contentType: false,
        //    contentType: "multipart/form-data",
        //    contentType: "application/x-www-form-urlencoded",
            processData: false,
            success: function (response) {
                if (response.success) {
                    window.location.href = "@Url.Action("Index", "BanksV62")";
                } else {
                    alert("Error occurred.");
                }
            },
            error: function (response) {
                alert("Request failed from create error.");
            }
        });
    }
}

This is my controller's action method's signature

[HttpPost]
public async Task<IActionResult> Create(BankViewModel bankViewModel)
{
    // here bankViewModel received object with null or default values not exact value that i have passed
}

And this is my view model:

public class BankViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Website { get; set; }
    public IFormFile? Logo { get; set; }
    public DateTime StartDate { get; set; }
    public int Stars { get; set; }
    public List<BranchViewModel> Branches { get; set; }
    public string? IdListToDelete { get; set; }
}

Is it really possible to post a custom object (not FormData) with photos through an Ajax call?? If possible - how can I do it?

I am trying to submit form data through an Ajax call and not passing FormData, but instead passing a custom object in the Ajax call.

This is my ajax call:

function submitData() {
    let isValid = true;
    var bankViewModel = {};
    
    {
        bankViewModel = {
            Name: $("#name").val(),
            Website: $("#website").val(),
            Logo: $("input#logo")[0].files[0],
      //      Logo: null,
            StartDate: $("#startDate").val(),
            Stars: $("#stars").val(),
            Branches: []
        };

        // branches
        $("#branchTable tbody tr").each(function (index, row) {
            const branch = {
                Name: $(row).find(".branch-name").val(),
                Email: $(row).find(".branch-email").val(),
                Status: $(row).find(".branch-status").is(":checked"),
                Photo: $(row).find(".branch-photo")[0].files[0]
            //    Photo: null
            };
        bankViewModel.Branches.push(branch);
        });

        console.log("++++++++BANK+++++++++");
    console.log(bankViewModel);
        console.log("+++++++++++++++++");
    }

    if (isValid) {
        $.ajax({
            type: "POST",
            url: "@Url.Action("Create", "BanksV62")",
     //       data: form,
        data: {bankViewModel},
       //     contentType: ,
            contentType: false,
        //    contentType: "multipart/form-data",
        //    contentType: "application/x-www-form-urlencoded",
            processData: false,
            success: function (response) {
                if (response.success) {
                    window.location.href = "@Url.Action("Index", "BanksV62")";
                } else {
                    alert("Error occurred.");
                }
            },
            error: function (response) {
                alert("Request failed from create error.");
            }
        });
    }
}

This is my controller's action method's signature

[HttpPost]
public async Task<IActionResult> Create(BankViewModel bankViewModel)
{
    // here bankViewModel received object with null or default values not exact value that i have passed
}

And this is my view model:

public class BankViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Website { get; set; }
    public IFormFile? Logo { get; set; }
    public DateTime StartDate { get; set; }
    public int Stars { get; set; }
    public List<BranchViewModel> Branches { get; set; }
    public string? IdListToDelete { get; set; }
}

Is it really possible to post a custom object (not FormData) with photos through an Ajax call?? If possible - how can I do it?

Share Improve this question edited Jan 8 at 21:07 marc_s 754k183 gold badges1.4k silver badges1.5k bronze badges asked Jan 8 at 11:11 FireFistAceFireFistAce 11 silver badge2 bronze badges 1
  • Why can't you use formdata? An alternative would be base64 encoding the image and passing it into your bankviewmodel as a string. – Nick Acosta Commented Jan 8 at 15:28
Add a comment  | 

1 Answer 1

Reset to default 0

If you want to send the file directly in js model, the most easily way is using the formdata. If you want to use other way, you should firstly convert the file to the byte64 or other format and then send it to the backend.

Encode the file and decode the file and save inside the server will use more resource than directly using the formdata in bytearray.

本文标签: Form Submission (cutom object not FormData) through Ajax in ASP NET Core MVCStack Overflow