0

I'm trying to use AngularJS in my web application and I have a few questions on how to get the implementation of the onClick event for my upload button.

View:

 <form action="" method="post" enctype="multipart/form-data">
        <table style="margin-top:20px">
            <tr>
                <td><label for="file">Filename:</label></td>
                <td><input type="file" name="file" id="file" accept=".csv" /></td>
                <td><button type="submit" value="Upload" ng-click="uploadFile()" /></td>
            </tr>
        </table>
    </form>

Controller (ASP.NET MVC):

 [HttpPost]
 public ActionResult Index(HttpPostedFileBase file)
 { 
    //CSvReader reads in contents of the file and adds them to a list
    //Stores the list in session
 } 

The part I'm stuck on is the implementation for the AngularJS script for the uploadFile() method.

I'm assuming on Click, I need to use an $http service that will post the data to my controller but I'm not sure how to do that. How do I pass in the necessary information from my view to my controller on the server side? Is there anything else I need to do in my angularJS script besides using that service?

I also mean to say is where would I put my onClick event inside my module code?

var myApp = angular
                .module("myModule", [])
                .controller("myController", function ($scope) {

                $scope.uploadFile = function () {
                    // your upload logic here
                    var data = {
                        //file? What should data be? 
                    };

                $http
                    .post('Home/Index', data)
                    .success(function (data, status, headers, config) {
                    })
                    .errors(function (data, status, headers, config) {
                    });
                };

            });
Kala J
  • 2,040
  • 4
  • 45
  • 85

1 Answers1

0

The onclick handler logic should go in your controller:

var myApp = angular
                .module("myModule", [])
                .controller("myController", function ($scope) {

                $scope.uploadFile = function() {
                // your upload logic here
                }

            });

As far as accessing the values of your form, you need to bind each form field to a model. However, file upload is not natively implemented in angular. There are several modules you can use to achieve that:

File Upload using AngularJS

Community
  • 1
  • 1
NGPixel
  • 392
  • 2
  • 9
  • Can I use what I using for file upload on server side code? Do I still need to do file upload in Angular? That is, I'm not sure what my upload logic should be on the client side/angular? – Kala J Dec 21 '15 at 05:17
  • You can do a standard file upload, with no logic in Angular, but that won't be async. – NGPixel Dec 21 '15 at 05:21
  • So how do I make it async then? – Kala J Dec 21 '15 at 07:37