价值不是来自剃刀ajax到行动方法

时间:2016-08-15 14:12:34

标签: jquery ajax asp.net-mvc razor

action方法中的id始终为null。在我做错什么的地方丢了。 action方法按预期调用。

jQuery函数:

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();

        }
    });
}

行动方法:

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);
}

3 个答案:

答案 0 :(得分:2)

您无需对数据执行JSON stringify。您可以按原样发送js对象。

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

现在由于这是一个GET请求,数据(js对象)将作为查询字符串值发送到服务器(例如:ListAppointments?Id=23

因此,当您{j}对象JSON.stringify进行调用时,它会返回字符串,如"{"Id":23}"。因此,用于ajax调用(使用查询字符串)的最终URL将为ListAppointments?{"Id":23}。你可以看到这是无效的。它应该是ListAppointments?Id=23

如果您仍想使用JSON.stringify(发送复杂数据),请指定contentType并使用POST方法。

另外我看到你在操作方法中将字符串参数值转换为int,为什么不使用int作为参数类型,因为你要发送数字数据?

public PartialViewResult ListAppointments(int Id)
{

}

答案 1 :(得分:0)

通过这样做,我有它的工作。不确定为什么stringify函数会阻止它工作:

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

            }
        });
    }

答案 2 :(得分:0)

您遗失的Content-Type:'application/json'但假设您已离开默认路线,则可以使用查询参数传递

function success(result) {
    var Id = $('#UserId').val();
    alert(data);
    $.ajax({
        type: "GET",
        url: "@Url.Action("ListAppointments", "Appointment")" + "?id=" + Id,
        data: data,
        success: function (result2) {
            $("#partialViewAppointments").html(result2);
            $('#example').DataTable();

        }
    });
}