New Razor Pages from javascript with posting data - javascript

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

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

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

Related

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.

ajax returns an html code instead of returning the response of the request to a url, in mvc 3

I have a problem when trying to make a request to a url created from mvc, this request is made to an actionresult of a controller, when I am in home ajax if it finds the address, but when I am in a site of my specific system , that is, I am in a section where the url is larger due to other parameters that are in the url, for example in a user profile, there ajax instead of finding the url that is linked to an actionresult return the html page, that is, return the html code, here are my codes
function guardarCalificacion(newidp, ratingp)
{
$.ajax({
type: 'POST',
url: 'saveRating',
data: {
newid: newidp,
rating: ratingp
},
beforeSend: function () {
},
success: function (data)
{
alert(data);
},
error: function ()
{ },
complete: function ()
{ }
});
}
and there are the route
routes.MapRoute(
"saveRating",
"saveRating/{newid}/{rating}",
new { controller = "Home", action = "SaveRating", id = UrlParameter.Optional }
);
in this url if it runs well
http://localhost:49439/Home/index
but in this it is not executed
http://localhost:49439/new/128/busqueda-numero-29
and finally the actionresult
public ActionResult SaveRating(int newid, int rating)
{
return Content(Methods.saveRating(newid, rating).ToString());
}

How to make a AJAX GET call in ASP.NET MVC application

I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});

call an Asp Action from javascript

I have a table that will use is populated by javascript when another table option is clicked. All of this works no problem, when I add the delete button to the table the onClick event fires but this isn't ever called in asp.net.
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/',
data:{ id:id }
});
}
please tell me where I've gone wrong.
I have tried
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/' + id
}
as well
UPDATE:
[HttpPost]
public async Task<IActionResult> LinkDelete(Guid id)
{
var pageId = _linkDataProvider.FindById(id).PublicPage.Id;
_linkDataProvider.Delete(id);
var page = await _pageDataProvider.FindById(pageId);
var viewModel = _pageDataProvider.ConvertToViewModel(page);
return View("Details", viewModel);
}
UPDATE2
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Flooring}/{action=Index}/{id?}");
});
You should specify http method in ajax settings. Try to change your javascript like below:
function DeleteLink(id) {
$.ajax({
type = 'POST',
url: '/PublicPages/LinkDelete/' + id
});
}
Update
If you prefer to use data:{ id:id } then you would need to create a model class:
public class DeleteModel
{
public Guid Id{get;set;}
}
[HttpPost]
public async Task<IActionResult> LinkDelete([FromBody]DeleteModel model)
....

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Categories

Resources