Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC controller method not receiving json data from $http post

This might be basic question but I couldn't find where the issue is. I am using .Net Core for by back end and angularJS for front end. below is my code.

HTML

<div ng-controller="loginController">
<input type="text" ng-model="email"><br />
<input type="text" ng-model="password"><br />
<input type="submit" ng-click="login()">
</div>

AngularJS Code

app.controller('loginController',['$scope','$http', function (scope, http) {

scope.login = function () {
    var req = {
        method: 'POST',
        url: '/Account/loginInfo',
        data: { email: scope.email, password: scope.password },
        headers: {
            "Content-Type": "application/json"
        }
    }
    http(req)

        .then(function successCallback(response) {

        }, function errorCallback(response) {

        });
};
}]);

Back end c#

[HttpPost]
public JsonResult loginInfo(string email, string password)
{
  //do something here
}

When I debug this I can see that payload is having the email and password values but anyhow they are not getting passed to the controller method. I can see that controller method is being hit but the values show as null.

things I have tried:

  • Setting the content type to "application/x-www-form-urlencoded"
  • Passing the data as Json object
  • Converting scope values to string

None of them seem to be working. anyone faced this kind of issue or expert opinion please.

Followed this post Angular JS Not Sending Data To Web Api . didn't quite get the approved answer or it is not related to my issue.

like image 286
krishna chaitanya Avatar asked Jun 26 '26 22:06

krishna chaitanya


2 Answers

You have to use the [FromBody] attribute with a model parameter.

public class Credentials
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public IActionResult Login([FromBody]Credentials creds)
{
    // do stuff
}

This is because in ASP.NET Core MVC the default content type is application/x-www-form-urlencoded (for handling HTML form data). The [FromBody] attribute tells the model binder to instead try and create the model from JSON content.

like image 162
Brad Avatar answered Jun 28 '26 13:06

Brad


You must create an Class or Interface to send several parameters

public class PostParams
{
    public string email { get; set; }
    public string password { get; set; }
}     
[HttpPost]
public JsonResult loginInfo([FromBody] PostParams params)
{
  //do something here

}
like image 41
Abel Valdez Avatar answered Jun 28 '26 13:06

Abel Valdez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!