I'm using ASP.NET Core 8. How to pass a model to controller through AJAX?
My code worked, but it's not code to transfer AJAX data to controller.
public class StudentModel
{
public int? id { get; set; }
public string? Stu_Name { get; set; }
public string? Stu_Address { get; set; }
public string? Sty_Gender { get; set; }
public int? Stu_Age { get; set; }
public string? Stu_Class { get; set; }
}
$.ajax({
type: "POST",
url: "/Student/Create",
//data: '{saveStudentdata:' + GetData + '}',
data: JSON.stringify({ saveStudentdata: GetData }),
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function (responce) {
if (responce.saveStatus == "Success") {
alert("Data Successfully Save...");
}
else { alert("Data not Save.."); }
},
error: function (error) {
alert(error);
}
});
Controller:
[HttpPost]
public JsonResult Create(StudentModel SaveStudentdata)
{
string Status = string.Empty;
try
{
Status = Studata.Createdata(SaveStudentdata);
return Json(new { saveStatus = Status });
}
catch (Exception ex)
{
return Json(new { saveStatus = Status, errorMassage = ex.Message });
}
}
Update: I updated my ajax code but still controller is getting called. Data is not getting transferred.
[FromBody] StudentModel SaveStudentdata. Another thing you need to change is at ajax calling use body asJSON.stringify(GetData){"id":1,"stu_Name":"name here","stu_Address":"address here","sty_Gender":"male","stu_Age":26,"stu_Class":"class here"}.