How to Post json data to MVC controller

Posted by laura@refactoredmedia.com on 28-Jan-2020 22:14

I have 2 javascript methods. One is a get method, and the other is a post. I was able to get data using the get method. But I cant retrieve the data from the post

my get method js

return fetch(sf_appPath +'ajax/getpublickey', {
method: 'get',
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
return response.json();
})

Controller

[HttpGet, Route("ajax/getpublickey")]
public JsonResult PublicKey()
{
return "key";
}

but havent been able to figure out how to get the data from the post.

My javascript

return fetch(sf_appPath + 'ajax/create-customer/', {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: {
Email: cardholderEmail,
PlanId: PlanId
}
})
.then(response => {
return response.json();
})

My controller

[HttpPost, Route("ajax/create-customer/")]
public JsonResult CreateCustomer(string email, string planid)
{
string s = "test";
return Json(s);
}

email and plan ID are always null. Any suggestions?

All Replies

Posted by hugo.aguirre@bray.com on 28-Jan-2020 22:43

public JsonResult CreateCustomer(string email, string planid)

{

string s = "test";

return Json(s);

}

You cant receive multiple parameters in post method you need create a class or get into dynamic object like

public JsonResult CreateCustomer(Dynamic parameters)

{

 string email = parameters.email;

 string planId = parameters.plan.Id;

 return Json(email + planId);

}

The best way is creating a class:

Public Class Whatever

{

  public string email {get;set;}

  public string planId {get;set;}

}

public JsonResult CreateCustomer(Whatever parameters)

{

 string email = parameters.email;

 string planId = parameters.plan.Id;

 return Json(email + planId);

}

Try it.

Posted by laura@refactoredmedia.com on 29-Jan-2020 16:50

I tried creating the class and when debugging I saw that the class was still null. I was able to get it to work using

Javascript  

return fetch(sf_appPath + 'ajax/create-customer/' + cardholderEmail + "/" + paymentMethod + "/" + PlanId, {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
.then(response => {
return response.json();
})

And my controller

[HttpPost, Route("ajax/create-customer/{email}/{paymentmethod}/{planid}")]
public JsonResult CreateCustomer(string email, string paymentmethod, string planid)
{
...etc
}

Posted by hugo.aguirre@bray.com on 29-Jan-2020 17:46
Posted by hugo.aguirre@bray.com on 29-Jan-2020 20:41

This was made in asp.net core.

If you are using asp.net Framework our controller file be different.

But is pretty similar.

Good luck.

This thread is closed