【问题标题】:Parameter is not passing by ajax call参数未通过 ajax 调用传递
【发布时间】:2013-08-14 08:44:03
【问题描述】:

我对控制器中的函数进行了 ajax 调用。我需要向该函数传递一个参数,但它没有发生。我的 ajax 调用:

 $("#BTN_Plus").click(function () {
     var CurrentPage = @Model.CurrentPage;
    $.ajax({
        type: "POST",
        url: "/Accueil/ListerIncidentsHotline",
        data: JSON.stringify(CurrentPage),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#Affichage").html(data);
        }
    });
});

我的控制器中的功能:

public PartialViewResult ListerIncidentsHotline( int page = 1)
    {
            int NextPage = 1 + page;
            const int PageSize = 10;
            int NumDossier = StructureData.DonneNumDossier((string)Session["Utilisateur"], (string)Session["MotDePasse"]);
            IEnumerable<IncidentHotline> ListeIncidents = StructureData.DonneIncidentsHotline(NumDossier);
            int NbreIncidents = StructureData.DonneNombreIncidents(NumDossier);
            ViewBag.NombreIncidents = NbreIncidents;
            var viewModel = new IncidentsPageInfo()
            {
                NumPages = (int)Math.Ceiling((double)ListeIncidents.Count() / PageSize),
                CurrentPage = NextPage,
                PageSize = PageSize,
                Incidents = ListeIncidents.Skip((NextPage - 1) * PageSize).Take(PageSize),
            };
            return this.PartialView(viewModel);

    }

当我对变量 CurrentPage 发出警报时,它显示了正确的值,但是当涉及到 ajax 调用时,我收到一条错误消息,指出参数为空。不知道有什么问题。

【问题讨论】:

    标签: ajax asp.net-mvc-4 controller


    【解决方案1】:

    以及您需要传递带有页面名称的可数值的数据,更改您的 ajax 数据

    $.ajax({ type: "POST", url: "/Accueil/ListerIncidentsHotline", data: JSON.stringify(CurrentPage), contentType: 'application/json; charset=utf-8', success: function (data) { $("#Affichage").html(data); } });

    将数据更改为 data: {page: CurrentPage}

    【讨论】:

    • 它有效!我只是不知道您的输入 ID 是什么!您必须使用类似页面:$("#CurrentPage").val()
    【解决方案2】:

    这更容易......

    $.get("/Accueil/ListerIncidentsHotline", { CurrentPage: @Model.CurrentPage } ).
      done(function (data) {
        $("#Affichage").html(data);
       });
    

    【讨论】:

    • 我不能使用 get 方法,因为在控制器中我已经有一个与 get 方法同名的函数。
    【解决方案3】:

    显然问题出在我的 ajax 调用上。所以我必须在 JSON.Stringify 方法中将参数的名称与其值连接起来,如下所示:

    $("#BTN_Plus").click(function () {
        var CurrentPage = @Model.CurrentPage;
        alert(CurrentPage);
        $.ajax({
            type: "POST",
            url: "/Accueil/ListerIncidentsHotline",
            data: JSON.stringify({ page: CurrentPage }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#Affichage").html(data);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多