SaiBand
SaiBand

Reputation: 5355

Upload Attachment and some additional parameters to MVC Controller

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.

Upvotes: 1

Views: 118

Answers (2)

Dinesh Prajapati
Dinesh Prajapati

Reputation: 99

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. :)

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

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()';

Upvotes: 1

Related Questions