Reputation: 95
How can I post data with javascript followed by loading a new Razor Page?
If I call a new Razor Page from an Ajax call then I can´t return that new Page.
How can I achieve this?
Thank you
Client: Javascript on Razor Page1.cshtml var ptFilter = (...); // $.ajax ??? call post Method of Page2
Server: another razor page Page2.cs
public async Task OnPostSendAsync([FromBody]PtFilter ptFilter) {
var data = await _ptService.GetData(ptFilter);
// RedirectToPage(data) ??;
// return Page(data) ??;
}
Upvotes: 2
Views: 735
Reputation: 258
Please take notes of the $ajax.url and the @ajax.success() that contains updatePreviewCart()
In the example below of a razor pages application I've been working on, I am adding a product item from the product page to a shopping cart view component that belongs on the navigation menu of the site. Once the item has been added to the shopping cart's database, the returning success block of the ajax call in the first code snippet will update the shopping cart on the nav bar. The ViewComponent is loaded via a BaseController as the component is being used within the _Layout.cs file.
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 View Component
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());
}
}
Upvotes: 1
Reputation: 1510
You can post data via $.ajax and receive a response from your controller, then just use window.location.replace(your page2 action url here)
Something like that:
$.ajax({
url: "...",
//...
}).done(function(data) {
//If needed, check received data, then
window.location.replace(your page2 action url here);
});
Upvotes: 1