来自javascript的带有发布数据的新Razor页面

时间:2019-01-29 17:18:10

标签: javascript c# razor-pages

在加载新的Razor页面之后,如何使用javascript发布数据?

如果我从Ajax调用中调用了一个新的Razor页面,那么我将无法返回该新页面。

我该如何实现?

谢谢

客户端:Razor Page1.cshtml上的Javascript var ptFilter =(...); // $ .ajax ???第2页的呼叫方法

服务器:另一个剃须刀页面Page2.cs

公共异步任务OnPostSendAsync([FromBody] PtFilter ptFilter) {

   var data = await _ptService.GetData(ptFilter);
   // RedirectToPage(data) ??;
   // return Page(data) ??;

}

2 个答案:

答案 0 :(得分:1)

您可以通过$ .ajax发布数据并接收来自控制器的响应,然后只需使用window.location.replace(your page2 action url here)

类似的东西:

$.ajax({
  url: "...",
  //...
}).done(function(data) {
  //If needed, check received data, then
  window.location.replace(your page2 action url here);
});

答案 1 :(得分:0)

请注意$ ajax.url和@ ajax.success()包含updatePreviewCart()

在下面正在处理的剃须刀页面应用程序的示例中,我将产品页面中的产品项添加到该站点的导航菜单中的购物车视图组件中。将商品添加到购物车的数据库后,第一个代码段中ajax调用的返回成功块将更新导航栏上的购物车。在_Layout.cs文件中使用组件时,通过BaseController加载了ViewComponent。

Products.html

$(".add-to-cart").on("click", function (element: any) {
    element.preventDefault();

    $.ajax({
        cache: false,
        type: "POST",
        url: "Products/?handler=AsyncAddToCart",
        data: { id: $(this).data("id") },
        beforeSend: xhr => {
            xhr.setRequestHeader("XSRF-TOKEN", ($('input:hidden[name="__RequestVerificationToken"]').val() as string));
        },
        success: (data) => {
            if (data.isSuccess) {
                toastr.success($(this).data("name") + " has successfully been added to your cart. <a href='/Index'>Go to checkout</a>");
                updatePreviewCart();
            } else {
                toastr.error(data.message);
            }
        },
        error: (xhr: any, ajaxOptions: any, thrownError: any) => {
            toastr.error("Unable to add items at this time. Please try again later or contact support if issue persists.");
        }
    });
});

UpdateCartPreview.js

function updatePreviewCart() {
    $.ajax(({
        cache: false,
        type: "GET",
        url: "/Base/GetCartViewComponent",
        success: (data) => {
            $("#preview-cart-container").html(data);
        },
        error: (xhr: any, ajaxOptions: any, thrownError: any) => {
            toastr.warning("Your preview cart is still updating. You should see your added item(s) shortly.");
        }
    }));
}

BaseController.cs

[Route("[controller]/[action]")]
    public class BaseController : Controller
    {
        [HttpGet]
        public IActionResult GetCartViewComponent()
        {
            return ViewComponent("Cart");
        }

        [HttpPost]
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1)}
            );

            return LocalRedirect(returnUrl);
        }
    }

Cart.cs查看组件

public class Cart : ViewComponent
    {
        private readonly ICartService _cartService;

        public Cart(ICartService cartService)
        {
            _cartService = cartService;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            return View("~/Pages/Components/Cart/Default.cshtml", await _cartService.GetCart());
        }
    }