AngularJS with C# MVC

The other day I tried using AngularJS with C# MVC to create this site.

SoundClip Creator

It was my first time using angularJs, here are some of the items I spent some time on

Here are some of the challenges I’ve faced

1) Creating a controller

Within, controllers need to belong to a module

This, will work


<div ng-app='moduleng-controller="controller">
var ngModule = angular.module("module",[]);
 function ($scope, $http)


This, will not work


<div ng-controller="controller">


function controller($scope){...}


2) Beware of version of MVC

Not all of them support posting using JSON natively

Symptom: Correct JSON strings are being sent, but in MVC controller all the arguments are null

Solution: Using MVC 2 Future Library

Or do what I did: use urlen encoding instead

StackOverflow Example

Make sure arguments match the argument names in the MVC controller

 var result = $http(
 { method: "post",
 headers: {'Content-Type':'application/x-www-form-urlencoded'},
 url: '/Home/Index/',
 transformRequest: function(obj) {
 var str=[];
 for (var p in obj)
 {str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));}
 return str.join("&");
 data: {arg1: $scope.arg1,
        arg2: $scope.arg2


3) Processing a file download

Since Ajax does not provide a good binary download support, I needed to create an extra Download action within the controller

MVC Download Action Explanation

// GET: /Home/Download
public ActionResult DownloadFile(string id)
var cd = new System.Net.Mime.ContentDisposition
// for example foo.bak
FileName = “generatedFile“,

// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
Response.AppendHeader(“Content-Disposition“, cd.ToString());
return File(new FileStream(Path.Combine(baseDirectory, id.ToString()), FileMode.Open), “MIME-String”);

See complete Mime Types here

AngularJS, on request.success

result.success(function (data)
var hrefDownload = ‘/Home/DownloadFile/‘ + data;
location.href = hrefDownload;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s