1

I have a MVC Controller with the following signature:-

[HttpPost]
public async Task<JsonResult> SaveBrochureAsAttachment(Guid listingId, HttpPostedFileWrapper attachmentFile)
{
     ///some logic
}

How do I make an ajax call and send the file attachment and additional listingId parameter. Currently I am only able to send the attachment like this:-

var uploadFile = function () {

    if ($('#attachmentFile').val()) {

    }
    else {
        alert('No File Uploaded');
        return;
    }

    var formData = new FormData($('#uploadForm')[0]);


    $.ajax({
        url: '/Listing/SaveBrochureAsAttachment',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert('File Uploaded');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $("#FileUpload").replaceWith($("#FileUpload").val('').clone(true));
            alert('File Uploaded Error');
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
}

Currently as you folks can see I am only able to send the attachment. How do I also send the Guid listingId to match the controller signature.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
SaiBand
  • 5,025
  • 15
  • 57
  • 76

2 Answers2

1

Try adding another formdata parameter:

formData.append("listingId", guidValue);

Provided you have the guid value accessible. You can use this to generate one from the client. Or create one from the server:

var guidValue = '@Guid.NewGuid()';
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • I also wrote about another alternative approach using the FileReader API; you can get the contents as a base64 string, which makes it easier to pass back to the server: https://onallthingsweb.wordpress.com/2017/06/26/ajax-file-uploads-with-html-5/ – Brian Mains Oct 09 '18 at 14:34
0

one approach would be to your controller accept viewmodel (a class) which contains different property you need. and use formdata.append required stuff to post to the server.

On Server side; you will need to use modelbinder so that you will get required stuff populated.

Refernce for modelbinder : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc

you can get more on google. :)