Search code examples
angularjsajaxasp.net-mvc-5httppostedfilebase

asp.net mvc with angular with multiple parameter ajax call HttpPostedFileBase file getting null value


Here i send an object and a file from my angular service:

 $scope.addProject = function () {
        {
            var project = {};
            project["Id"] = $scope.Id;
            project["ProjectCode"] = $scope.ProjectCode;

            var file = $scope.myFile;
            projectModelService.saveProject(project,file)
            .success(function (data) {

            })
            .error(function (xhr) {
                $ngBootbox.alert('Error in saving data');
            });

        }
    };

and in my angular service:

saveProject: function (project) {
             var parameters = { project: project, file: file };

             var fdata = new FormData();
             fdata.append('file', file);

             var param = { project: project, file: fdata.append('file', file) };
            return $http({
                url: '/Project/CreateProject',
                method: 'POST',
                data: project
               // contentType: false, // Not to set any content header
               // processData: false, // Not to process data
               // transformRequest: angular.identity,
               // headers: { 'Content-Type': undefined },
                dataType: "json",
                data: JSON.stringify(param)

            })
        },

and in my Project/Createproject :

  public JsonResult CreateProject(Project project, HttpPostedFileBase file)
    {
     }

Now problem is in every situation my HttpPostedFileBase file return null. But if i pass the file by single parameter as :

 uploadProjectModelList: function (file) {
            var fdata = new FormData();
            var url = '/Project/UploadProjectFGModelListExcelFile';
            fdata.append('file', file);
            return $http.post(url, fdata, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
        }

it shows the file value but whenever using it to pass multiple parameter as like project object file are found but project object was null. how can i pass multiple parameter as a object and a file from ajax to asp.net controller in MVC5?


Solution

  • You could pass the project parameter as part of the FormData payload:

    var fdata = new FormData();
    var url = '/Project/UploadProjectFGModelListExcelFile';
    fdata.append('file', file);
    
    fdata.append('project.Id', project.id);
    fdata.append('project.Foo', project.foo);
    fdata.append('project.Bar', project.bar);
    fdata.append('project.Baz.Bazinga', project.baz.bazinga);
    ...
    
    return $http.post(url, fdata, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    });
    

    Standard field naming rules apply for the ASP.NET MVC model binder.