Search code examples
ajaxasp.net-mvc-4form-data

How to receive multiple Data in controller side using FormData(Ajax)?


My ajax has used FormData and append multiple Field value (like Text-box,label,File) in single(FormData) object. and i have posted that data at server side but

How to receive same data object in controller?

FormData variable :

var uploadFile = new FormData();
        var files = $("#UploadFile").get(0).files;
        if (files.length > 0) {
            uploadFile.append("Doc", files[0]);
        }
  FileUpload(uploadFile);

Javasacript method Ajax Call :

 function FileUpload(uploadFile)
{
    var url = '@Url.Action("UploadCsvFile")';

    $.ajax({
        url:url,
        contentType: false,
        processData: false,
        data:uploadFile,
        type: 'POST',
        success: function () {
            alert("Successfully Added & processed");

        }
    });

My Question is....if in case,My ajax has more Data, How to receive the same data in controller side and what, if i want to use specific Data object.


Solution

  • You can receive customized forms that are quite complex

    It will work in two parts:

    Part 1 - Extending the html FormData:

    uploadFile.append("TextData", "This is my text data");
    

    Part 2 - Extending your controller:

    I assume your model would look something like this:

    public class MyModel
    {
         public HttpPostedFileBase Doc{ get; set;}
    }
    

    Now just add your custom data to it:

    public string TextData {get;set;}
    

    And in your controller method:

    public JsonResult MyUploadMethod(MyModel model)
    {
        /*From here you will have access to the file and the text data*/
    }
    

    Hope it helps. Ask me any questions if you need help.