Created Asp Net Core (6) Web Application (MVC), code in Index.cshtml:
<button onclick="Get()">Send</button>
<script>
function Get(){
var results = new Array();
var emp1 = { "ID": "12", "Name": "Manas" };
var emp2 = { "ID": "2", "Name": "Tester" };
results.push(emp1);
results.push(emp2);
console.log(results);
$.ajax({
url: 'Home/GetQuiz',
data: JSON.stringify(results),
type: 'POST',
contentType: "application/json",
dataType: 'json',
success: function (resp) {
//request sent and response received.
}
});
}
</script>
HomeController:
[HttpPost]
public IActionResult GetQuiz(List<Employee> empList)
{
return RedirectToAction("Index","Home");
}
I get into the action of the controller, but the list is empty, please tell me why ? On the Layout page, the link to the library is connected:
CodePudding user response:
since you are using "application/json" content type, you should use frombody attribute in your action, and redirect is not working when ajax is used, try just to return action
public IActionResult GetQuiz([FromBody] List<Employee> empList)
{
return Index();
}
CodePudding user response:
since your content type is "application/json", use the [FromBody]
attribute in the controller action method. Read more on Microsoft docs.
And since you are on the Home controller already, you do not need to redirect to action, just return the index.
public IActionResult GetQuiz([FromBody] List<Employee> empList)
{
return Index();
}