Click here to Skip to main content
15,908,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi There, can some please help me how to pass serialize form data , file uploads paths and rest of the parameter like
var OfficeHolder_id="123", var AccountDetail_Id="789", var contact_person_id="8910" to the controller method below using ajax post method.
some of the sample code is below


view code
@using (Html.BeginForm("SaveApplication", "CreateApplicationFromSearch", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

<input type="file" id="specific_Item" name="specific_Item" multiple="multiple"/> 
			<input type="file" id="Position_Description" name="Position_Description" multiple="multiple"/>
                        <input type="file" id="Employment_Contract" name="Employment_Contract" multiple="multiple"/>






controller method
[HttpPost]
public ActionResult SaveApplication(tr_applications Application,
IEnumerable<httppostedfilebase> specific_Item, IEnumerable<httppostedfilebase> Position_Description,
IEnumerable<httppostedfilebase> Employment_Contract,string OfficeHolder_id, int? AccountDetail_Id, string contact_person_id)

What I have tried:

$('#btnSaveClose').click(function () {
var fileUpload = $("#Resolution_ToApply").get(0).files;
var files = fileUpload.files;
var fileData= new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: "/CreateApplicationFromSearch/SaveAndCloseApplication",
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (response) {
if (response != null && response.success) {
} else {
alert(response.responseText);
}
},
error: function (response) {

alert("error!" + response.responseText);}
});
});
Posted
Updated 17-May-17 2:05am
v3

1 solution

Try:
JavaScript
$('#btnSaveClose').click(function(evt){
    // Stop the button from submitting the form:
    evt.preventDefault();
    
    // Serialize the entire form:
    var data = new FormData(this.form);
    
    $.ajax({
        url: "/CreateApplicationFromSearch/SaveApplication", // NB: Use the correct action name
        type: "POST",
        data: data,
        processData: false,
        contentType: false,
        success: function(response) {
            ...
        },
        error: function(response) {
            ...
        }
    });
});

Using FormData Objects - Retrieving a FormData object from an HTML form[^]
 
Share this answer
 
Comments
Member 12697982 17-May-17 17:41pm    
Thanks a ton , this solution worked, i was struggling with this problem , never ever thought its going to be so simple

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900