0

On my front end, I have a simple button:

<input class="btn" value="Something" ng-click="doStuff('myNameisEarl')" />

My Angular.js is as follows:

$scope.doStuff = function (name) {

    $http.post('/api/callToApi', name)
    .then(function (response) {
        // Do something with response
    }, function () {
        console.log("Failure");
    });
}

Then my back end C# Controller is:

[HttpPost("api/callToApi")]
public IActionResult Get(string name)
{
    return Ok(_context.MyDBTable.Where(a => a.Name.Equals(name)));
}

Unfortunately, when I pass in name from my angular code to the C# function, string name is null.

Why is that? What's going wrong here?

3 Answers 3

1

Since you are posting data from body which we normally do, you can explicit say [FromBody] in action method.

$scope.doStuff = function (name) {
    var data = JSON.stringify({name: name}); // Convert to a JSON string
    $http.post('/api/callToApi', data)
    .then(function (response) {
        console.log("Success");
    }, function () {
        console.log("Failure");
    });
}

[HttpPost("api/callToApi")]
public IActionResult Post([FromBody] string name)
{
    return Ok(_context.MyDBTable.Where(a => a.Name.Equals(name)));
}

FYI: You want to name action method as Post instead of Get for best practice.

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

2 Comments

@RamSingh he is using the POST method, if you check the code carefully. My answer is also about the Post. I'm not really understanding your comment. Could you please elaborate more?
FYI: You want to name action method as Post instead of Get for best practice you added this line so i added my comment. skip if you were trying to add more info. i am going to delete it in that case
0

You can send the name in the querystring. the querystring key should match with the parameter name.

This should work.

$scope.doStuff = function (name) {

    $http.post('/api/callToApi?name='+ name )
    .then(function (response) {

           var responseData = response.data;
           console.log(responseData);

        }, function () {
        console.log("Failure");
    });
}

Comments

0

I think this should solve the problem

$.ajax({
        url: '/api/controller/action',
        type: "POST",
        data: {name: variable}
    }).done((data) => {
        successCallBack(data);
    }).fail((response) => {
        failureCallBack(response);
    });

This should work.

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.