【问题标题】:JQuery/Ajax post in Razor page and redirect to returned view from MVC Action (aka form submitting)在 Razor 页面中发布 JQuery/Ajax 并重定向到从 MVC 操作返回的视图(又名表单提交)
【发布时间】:2019-02-08 04:25:25
【问题描述】:

我通过 JQuery 或 AJax 将 json 数组发布到 MVC Action,Action 正确处理请求。但是,然后 MVC Action 正在返回一个视图,我需要重定向到这个视图(或用它替换一个正文),但我不知道如何。

所以,除了返回值之外,该操作运行良好:

    [HttpPost]
    public ActionResult CreateGet(List<string> itemIds)
    {
        List<TempItem> items = new List<TempItem>();
        foreach (string item in itemIds)
        {
            items.Add(CallApi.Get(Request.Cookies["jwt"], "tempitems", item.ToString()).Content.ReadAsAsync<TempItem>().Result);
        }
        Invoice inv = new Invoice()
        {
            IsSupplement = items[0].IsSupplement,
            Date = DateTime.Now,
            Employee = CallApi.Get(Request.Cookies["jwt"], "employees/getprofile").Content.ReadAsAsync<Employee>().Result,
            InvoiceItems = new List<InvoiceItem>()
        };

        foreach(TempItem item in items)
        {
            inv.InvoiceItems.Add(new InvoiceItem { Amount = item.Amount, ProductId = item.ProductId, Product = item.Product });
        }
        return View(inv);
    }

还有 razor 页面中的脚本,它收集选定的 id 并将它们发布到操作中。 发布后没有其他任何反应,即使没有调用警报,即使视图页面存在并且我在控制台中看不到失败。

    function CreateInvoice(id) {
        var selected = $('#' + id).DataTable().rows('.selected').data();
        var items = [];
        for (i = 0; i < selected.length; i++) {
            items.push(selected[i][0]);
        }
        var postData = { itemIds: items };

        $.ajax({
            type: "POST",
            url: "/Invoices/CreateGet",
            data: postData,
            success: function (data) {
                alert("success");
                window.location.href = data.url;
            },
            dataType: "json",
            traditional: true
        });
    }

更新

好吧,我放弃了这些废话,坚持使用在 URL 中传递 id 数组的 GET 请求。我想我只是做错了。

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc razor


    【解决方案1】:

    您应该将ActionResult 更改为JsonResult。 然后像这样返回:

    return Json(new {url: "yoururl", inv: yourdata}, JsonRequestBehavior.AllowGet);
    

    【讨论】:

    • 您在 AJAX 调用中使用 url: "/Invoices/CreateGet" 以便您需要在操作中返回 JsonResult。
    • 问题是我设法在 ajax 请求中获得成功,并且我返回的数据包含urlinvoice 对象。我可以windows.location.href = data.url,所以页面重定向到正确的位置,但我如何也将发票对象传递到这个页面?
    • 我在您的源代码中看到,发票对象中没有 url?
    【解决方案2】:

    如果您不需要在实际页面中对 ajax 调用返回的数据执行任何操作,则不应使用 ajax 调用。您可以在后端使用提交请求和重定向页面到新页面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多