user1490835 user1490835 - 3 months ago 15
jQuery Question

value not coming from razor ajax to action method

Id in the action method is always null. lost where i am doing anything wrong. action method is called as expected.

jQuery function:

function success(result) {
var Id = $('#UserId').val();
var data = JSON.stringify({ 'Id': Id });
alert(data);
$.ajax({
type: "GET",
url: "@Url.Action("ListAppointments", "Appointment")",
data: data,

success: function (result2) {
$("#partialViewAppointments").html(result2);
$('#example').DataTable();

}
});
}


Action Method:

public PartialViewResult ListAppointments(string Id)
{
var userId = Convert.ToInt32(Id);
var o = (from s in db.tblAppointments.ToList()
where s.UserId == userId
select new AppointmentViewModel { AppointmentInstructorName = s.InstructorName, AppointmentLessonAddress = s.Address, LessonDateTime = s.LessonDate, UserId = s.UserId, Id = s.ID });

return PartialView(o);
}

Answer

You do not need to do JSON stringify on your data. You can send the js object as it is.

var d ={ Id:  $('#UserId').val()};
$.ajax({
            type: "GET",
            url: "@Url.Action("ListAppointments", "Home")",
            data: d
            success: function (result2) {
              $("#partialViewAppointments").html(result2);
              $('#example').DataTable();
            }
   });

Now since this is a GET request the data (the js object) will be send as a querystring values to the server (Ex : ListAppointments?Id=23)

So when you do JSON.stringify call on that js object, It will return a string like "{"Id":23}". So your final url used for the ajax call(with the querystring) will be ListAppointments?{"Id":23}. You can see that this is not valid. It should be ListAppointments?Id=23

If you still want to use JSON.stringify (to send complex data), specify contentType and use POST method.

Also i see you are converting the string param value to int in your action method, why not use int as parameter type since you are sending numeric data ?

public PartialViewResult ListAppointments(int Id)
{

}