Reputation: 423
I have read a lot of questions regarding similar issues, but none of them seems to work for me.
I am receiving null
for the movie object in the post action method.
This is my controller:
public class MovieController : Controller
{
[Route("movies/all")]
[HttpGet]
public ActionResult All()
{
List<string> movies = new List<string>();
movies.Add("Some Movie");
movies.Add("Diamond Team");
//Get movies
return Ok(movies);
}
[Route("movies/post")]
[HttpPost]
public ActionResult Post([FromBody] Movie movie)
{
Console.WriteLine(movie);
List<string> movies = new List<string>();
movies.Add(movie.title);
//Get movies
return Ok(movies);
}
public ActionResult Index()
{
return View();
}
}
This is the Movies class:
public class Movie
{
public string title { get; set; }
public float rating { get; set; }
public int year { get; set; }
public Movie(string title,float rating, int year)
{
this.title = title;
this.rating = rating;
this.year = year;
}
public Movie()
{
}
}
This is the post request (using postman), I have tried either application/json
and application/json; charset=utf-8
as the Content-Type but in both cases I have received null for the movie object:
{
"title":"Some Movie",
"rating":"1.87",
"year":"2011"
}
How can I fix this?
Upvotes: 0
Views: 523
Reputation: 11339
Please try to change your request JSON to this:
{
"title":"Some Movie",
"rating":1.87,
"year":2011
}
Upvotes: 1
Reputation: 51
in the postman you can use different way to call method. Click on code button and choose one of way to call method.
you can use jquery and put code onto section....
Upvotes: 0
Reputation: 51
Your model must first be serialized and then passed to data in ajax call. this is one sample, You have to change the model according to your needs....
$("#btnPost").click(function() {
var employee = new Object();
employee.Name = $('#txtName').val();
employee.Address = $('#txtDesignation').val();
employee.Location = $('#txtLocation').val();
if (employee != null) {
$.ajax({
type: "POST",
url: "/JQueryAjaxCall/AjaxPostCall",
data: JSON.stringify(employee),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response != null) {
alert("Name : " + response.Name + ", Designation : " + response.Designation + ", Location :" + response.Location);
} else {
alert("Something went wrong");
}
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
});
Upvotes: 0