2

I have looked around, but have not found anything (Angular post) that can actually make a successful call to a MVC Controller. I know there are a lot of Angular/.Net devs out there. Can I get some help?

Let's keep answers bare bones simple!!!

If I set a linebreak on the controller, I can see that this code is not actually hitting the controller.

HTML

<!-- I click this button -->
<input type="button" value="click" onclick="postit()" />

Javascript/Angular Post

function postit() {
 $http({
        method: 'POST',
        url: 'Home/Give/',
        data: { id: 4 }
    }).success(successFn).error(errorFn);
}

function successFn() {
    alert("success");
}

MVC C# Controller

    [AcceptVerbs("OPTIONS")]
    public ActionResult Give(int id)
    {
        var response = "some response" + id.ToString();
        return Json(new JavaScriptSerializer().Serialize(response)); 
     }
7
  • Don't know Angular much, so I am sure someone else will help you out. Why are you accepting verbs of options, and not POST as well? Commented Aug 22, 2014 at 22:13
  • 1
    I find that using WebAPI is much better than using MVC for AJAX calls in angular. Commented Aug 22, 2014 at 22:14
  • "OPTIONS" was recommended in another SO answer for Angular posts. I am trying to stack odds in my favor :) Commented Aug 22, 2014 at 22:17
  • Also I saw the WebAPI controller example, but I am hoping to use standard MVC controller if it's possible (will resort that way if no other method works). Commented Aug 22, 2014 at 22:18
  • The OPTIONS verb is there to enable CORS. You should put also [HttpPost] to enable that action to receive posts. If that doesn't work, please tell us what is the response to the endpoint, you may do that by checking the Network tab on Chrome's developer tools. Commented Aug 22, 2014 at 22:19

3 Answers 3

4

king Puppy, I've seen a few responses that dictate that the controller parameters should be an object that matches the object that is being sent, however, it seems that it's a little more forgiving than that. Consider the following example (I've updated your function a little):

Javascript:

$scope.postIt = function() {
  var data = {
    id = 4
  };

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


function successFn() {
  alert("success");
};

function errorFn() {
  alert("error");
};

MVC:

 public ActionResult Give(int id)
 {
   var response = "some response" + id.ToString();

   return Json(new JavaScriptSerializer().Serialize(response)); 
 }

If you set a breakpoint, you will see that the id passed in is 4.

If you needed to pass in an object (so more than just one id), you could either create a matching class or struct on the controller side, or have multiple parameters (provided that they are simple value types) ie:

public JsonResult Give (int id, int reasonId)
{
 ... 
}

Anyway, I realize the post is old, but perhaps it will help you or others.

Sign up to request clarification or add additional context in comments.

Comments

1

@kingPuppy this is my way to how to make angularjs post to mvc controller

first, html button for passing the angular js button click function;

<button class="btn btn-info" id="runButton" ng-click="runService('Hi')">Run</button>

so runService angular click (ng-click) function;

// Operation Type is my mvc controller's param
$scope.runService = function (optionType) {
    $http({
        url: '/System/RunService',
        method: "POST",
        data: {operationType : optionType}
    }).then(function onSuccess(response) {
        // Handle success
        console.log(response);
    }).catch(function onError(response) {
       // Handle error
       console.log(response);
    });
}

And finally this is system controller's action;

NOT : Dont forget to [HttpPost] attribute

[HttpPost]
public ActionResult RunService(string operationType)
{
    // Codes
    Response.StatusCode = 200;
    return Json(JsonRequestBehavior.AllowGet);
}

Hope this could help to you for how to make angular post to mvc controller. Thanks.

Comments

0

There is nothing special you have to do to get Angular to post to a standard MVC controller, and in fact I have several Angular/MVC apps that are using code almost identical to what you have above to POST to controllers that work fine.

I would use Firebug to confirm that your app is posting to the right place. One thing I noticed is that you might not want that trailing / at the end of your URL (so Home/Give instead of Home/Give/)

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.