Using AJAX, can we POST to a method in a ViewComponent? - c#

I have a ViewComponent called WatchList. It's being called in a page under a route named Request.
This is what the URL typically looks like:
And this is how I'm setting up the ViewComponent:
#await Component.InvokeAsync("WatchList", new { requestId = Model.RequestInput?.RequestId })
I'm attempting to make an AJAX POST from the ViewComponent:
$.ajax({
type: "POST",
url: "Request/WatchList?handler=GetMyself",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
But I'm running into a "XML Parsing Error: no root element found" error.
Location: http://localhost:12227/.../.../Request/WatchList?handler=GetMyself
I can't tell if I'm getting the route wrong, or if I can't call ViewComponent methods from AJAX.
Here is my structure:
Any ideas what I'm doing wrong here?

As Chris said , you can't use AJAX from the ViewComponent page to get into a method in the view component class.But you could try the following workaround which maybe you want , use the retrun ViewComponent(" ViewComponentName",new{ paramater1,paramater2...}); in a PageHandler to call the InvokeAsync method in the ViewComponent Class.

Related

AJAX Request to Method Contained in Class File

I'm trying to make an AJAX request on a Razor Page, calling a method contained in separate class file (NOT in the pagemodel for the page - as I eventually want to make the same request from multiple different pages).
Unfortunately, the request fails. I think it may have to do with the syntax I've used, or perhaps the class I'm trying to call being of the wrong type. Note that the request DOES work if I change the url to a method in the pagemodel (no other changes required).
I'm fairly new to ASP.NET Core Razor Pages, and AJAX requests, so if there's a fundamental misunderstanding here, let me know.
AJAX Request Code (jQuery):
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Tools/Redirect?handler=AccessRedirect',
type: 'GET',
success: function (data) {
alert("Request Success, Data = " + data);
},
error: function () {
alert("Request Failed");
}
});
})
(I've also tried url: /Tools/Redirect/AccessRedirect using a method simply called AccessRedirect, with the [HttpGet] attribute, but that didn't work either)
C# Class Code (File is Redirect.cs in folder Tools):
public class Redirect
{
public JsonResult OnGetAccessRedirect()
{
return new JsonResult("test");
}
}
Any help is greatly appreciated. Thanks.
Your fundamental misunderstanding is that Razor Pages requests must target a handler method in a PageModel class. You can't map URLs to arbitrary methods in class files. Handler methods must be in a class that derives from PageModel, and they must follow certain conventions.
You can read more about handler methods in Razor Pages here: https://www.learnrazorpages.com/razor-pages/handler-methods
If you have code that you want to centralise, you can put that in a C# class, and then call the method in your handler method

Ajax not recognized in JQuery file

I uploaded to GitHub days ago an MVC project, I've downloaded it again, and want to set some new functions using JQuery Ajax, but now when I'm trying to do something like this:
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/"
}).success(function (result) {
alert(result.testing)
})
});
An exception is thrown: Object doesn't support property or method 'success'.
I think that something is wrong with JQuery, when I'm going to write $.ajax inside a function the keyword ajax is not displayed, instead Intellisense shows other keywords like attr etc. Normally the keyword ajax is displayed from Intellisense.
I've been trying uninstaling and installing JQuery again and nothing happened, I've check the BundleConfig class to check if the JQuery files are added and they are there, I've installed unobtrusive ajax and have added it to BundleConfig class too and still the problem continues... What it could be??
Try it like this, putting the success inside ajax definition
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/",
success: {
function (result) {
alert(result.testing);
}
}})})

JSON data POST to Web API works in Fiddler but "Not Found" error from JQuery AJAX

my stuff works fine with Fiddler and I get desired result. But when i do it on web page thru JQuery AJAx, it says "Not Found". I am struggling since sometime but couldn't get around.
My Controller method is like this
[Route("AddDonors/")]
[HttpPost]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
This is how i am calling from web page
var userInput = { 'FullName': 'Lakshman', 'Mobile': '9924210053' };
$.ajax({
type: "POST",
url: "/AddDonors",
data: userInput,
error: function (result) {
alert(result);
},
datatype: "json"
});
this is the model class
public class localDonor
{
public String FullName { get; set; }
public String Mobile { get; set; }
}
API registering and other settings are just fine since this works in fiddler.
Please help. Thanks.
I strongly suspect that the url in your AJAX request is to blame (404 - Not Found) the request can't be routed to a controller for processing.
Without knowing what your full controller looks like and if you have a RoutePrefixAttribute on this specific controller I can't say what the url should be.
I would suggest you monitor network traffic in your browser developer tools (press F12) and compare the request url for your failing POST request to those of your successful requests in Fiddler
If your webpage is created in ASP.Net MVC as part of the same web project you may want to generate the url server side in future see Construct url in view for Web Api with attribute routing. The #Url helper is only available within your .cshtml files though so you will not be able you shift your JavaScript code to a separate .js file.
i was able to solve the issue by changing the url to url: "AddDonors",
Try to put [WebMethod] attribute.
[Route("AddDonors/")]
[HttpPost]
[WebMethod]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
Hope this works!
Try this for your POST data
var userInput = JSON.stringify({ 'FullName': 'Lakshman', 'Mobile': '9924210053' }),
I had the same error.
As you are using ASP.NET, try making all AJAX calls using the #Url.Action helper.I don't know why, but in some situations in ASP.NET passing the URL as a String doesn't work.And try passing your data like the code belowYour modified code should look something like this:
$.ajax({
type: "POST",
url: "#Url.Action("AddDonors", "ControllerName")",
data: { localDonor: userInput },
error: function (result) {
alert(result);
},
datatype: "json"
});

Jquery call to Controller of MVC: ReferenceError: url is not defined

I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?

Can't access asp controls from static method, but when I remove static, ajax call won't work

I have a method called getPersonInfo and it's header looks like this:
[WebMethod]
public static Hashtable getPersonInfo(int personID)
{
}
The problem I am having is that this method cannot access my asp.net controls. So of course I remove the "static" keyword. But then my ajax calls fail since it's not a static method any more. Any suggestions?
EDIT: After reading and searching for a bit, I've realized that it won't work. What I am asking is if there is another way of maybe getting the final result, as for now I'm unsure of how to do that.
This is fundamentally impossible.
AJAX methods do not run the page lifecycle, so the controls don't actually exist on the server.
Instead, you need to manipulate the page on the client.
You need to pass the values of controls to the getPersonInfo method from client side. For ex: if its JQuery ajax call, additional parameters can be passed using "data" property. Ofcourse, again the getPersonInfo method signature needs to be modified accordingly.
$.ajax({
url: 'adduser.aspx/getPersonInfo',
data: { personID: $('txtPersonId').val() }, //pass additional parameters here
type: "POST",
success: function (template) {
alert('success'); },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});

Categories

Resources