0

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.

2
  • What is at ModelState property in your controller? If some error occurs during bind the body to the action parameter it will be added to ModelState errors. Try to add [FromBody] in the parameter too: [FromBody] StudentModel SaveStudentdata. Another thing you need to change is at ajax calling use body as JSON.stringify(GetData) Commented Apr 4 at 17:46
  • You can check the request and posted data from browser dev tool network tab, and make sure if the posted data is as expected in request body, like this {"id":1,"stu_Name":"name here","stu_Address":"address here","sty_Gender":"male","stu_Age":26,"stu_Class":"class here"}. Commented Apr 8 at 5:59

1 Answer 1

0

I think your issue lies in a mismatch between the client-side and server-side. In your AJAX call, you are sending a JSON object that looks like this: { "saveStudentdata": { ... your student data ... } }.

You have wrapped your actual student data inside a property named saveStudentdata. Your controller action public JsonResult Create(StudentModel SaveStudentdata) is expecting a StudentModel object directly.

The model binder looks at the incoming data and tries to map its properties (id, Stu_Name, etc.) to the SaveStudentdata parameter. To me, it seems there is extra wrapper on the client-side, the model binder doesn't find a direct match and SaveStudentdata ends up being null or empty etc.

I reference solutions at stackoverflow here source via Stackoverflow

Please try this and see if it helps.




Controller:
[HttpPost] 
public JsonResult Create([FromBody] StudentModel saveStudentdata)
{
 string status = string.Empty;
 try {
 // Your model binding should now work, and saveStudentdata will be populated.
if (!ModelState.IsValid){
  return Json(new { saveStatus = "Error", errorMessage = "Invalid data" });
}
status = Studata.Createdata(saveStudentdata);
return Json(new { saveStatus = status });
    }
catch (Exception ex)
    {
 return Json(new { saveStatus = "Error", errorMessage = ex.Message });
    }
}






Ajax

// Assuming 'GetData' is a JavaScript object with properties
// that match your StudentModel (e.g., Stu_Name, Stu_Address)

$.ajax({
 type: "POST",
url: "/Student/Create",
// Send the object directly. JSON.stringify will convert it to a JSON string.
data: JSON.stringify(GetData),
// Ensure the content type is set to application/json
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.saveStatus === "Success") {
alert("Data Successfully Saved...");
} else {
alert("Data not Saved.. Error: " + response.errorMessage);
        }
    },
 error: function (xhr, status, error) {
// More descriptive error handling
alert("An error occurred: " + xhr.responseText);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.