DotNetCurry Logo

Posting Data & AngularJS Custom Directives in an ASP.NET MVC application

Posted by: Sumit Maitra , on 4/18/2014, in Category ASP.NET MVC
Views: 60738
Abstract: This article demonstrates how to use AngularJS to Post Data and use AngularJS Custom Directives in an ASP.NET MVC application.

In our previous article, Getting Started with AngularJS in ASP.NET MVC - Part 1 we explored AngularJS in a plain vanilla ASP.NET MVC Twitter application. The article talked about basic data binding and retrieving of data, and introduced AngularJS, walking through some core Angular features like Directives, Modules, Services and $Resource Provider.

In this article, we will explore how to use AngularJS to Post Data and use AngularJS Custom Directives in an ASP.NET MVC application.

3rd and final part of this article - Defining AngularJS Routing in an ASP.NET MVC application

This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free tutorials from experts


Posting Data

Before we get into Directives, let’s first add another functionality in our little Twitter Reader. The ability to send Tweets. So far we have used the $resource service’s query function. As we know, the resource function can also do GET, POST, PUT etc. Following is the map of actions to the HTTP verbs

{ 'get': {method:'GET'},

'save': {method:'POST'},

'query': {method:'GET', isArray:true},

'remove': {method:'DELETE'},

'delete': {method:'DELETE'} };

(Source: Angular JS Documentation)

So to post data, we need to simply call the save function on our resource instance. However there is a slight gotcha. The $resource object expects all the functions to post to the same URL. In MVC terms, this means posting to the same action method with different HttpGet/HttpPost/HttpPut etc attributes.

In our code, currently the HomeController uses GetTweets method to get the Data. Now Posting to a URL called GetTweets is semantically icky. So let’s update the Controller method to be called just Tweet. So we will do GET, POST, PUT etc. requests to the url /Home/Tweet.

Next we update our TwitterService to access the new URL

ngTwitter.factory("TwitterService", function ($resource)
    return {
        timeline: $resource("/Home/Tweet")

Now if we run the Application, we should get the same UI where the latest 20 tweets are shown on screen.

Adding a Tweet Field

To send out Tweets, we need an input box and a Tweet button. To do this, we add the following markup to the Index.cshtml