Call non static method in javascript from code behind in asp.net - javascript

I am having a non static method in aspx.cs file and want to call that method using javascript/jQuery.
I have seen many examples but none of them help i getting error like internal error 500 in javascript console.
here is the code
method in aspx.cs file
public void methodname()
{
// populating repeater
rp.DataSource = datatable;
rp.DataBind();
}
and in aspx file
function updateRepeater() {
console.log("update called");
$.ajax({
type: 'POST',
url: "aspx/methodname",
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
success: function (result) {
console.log("Success");
},
error: function (msg) {
console.log("Error");
}
});
}
but its not working i have also tried web method but it work with only static methods so can't use that.
can anyone tell me how to do this or i m doing anything wrong.
the error i get in console is
jquery-3.5.1.min.js:2
POST http://localhost:1003/foldername1/foldername2/PageNAme.aspx/MethodName 500 (Internal Server Error)

Related

Using AJAX call in MVC5

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>

AJAX call a ASP MVC action

I try to call a ASP MVC action from outside of the domain via ajax.
Setup
I have hosted a MVC application with this action inside:
[HttpPost]
[AllowAnonymous]
public ActionResult AjaxLogin(LoginViewModel model)
{
[..Login stuff..]
return Json(new { Url: "...", Result: "..." });
}
Usage
For testing I try a manuell call with a HttpRequester addon from Firefox, with this result:
It is working correct and the answer is as expected. So now I want to made an ajax call from a second web page (different domain).
My jquery (2.2.0) ajax call looks like this:
var requestData = {
model: {
Email: emailValue,
Password: passwordValue
}
};
var requestPlain = JSON.stringify(requestData);
$.ajax({
url: json_login_url,
data: requestData,
method: 'POST',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result, textStatus, jqXHR) {
[...]
},
error: function (jqXHR, textStatus, errorThrown) {
[...]
},
beforeSend: function (jqXHR, settings) {
return true;
},
complete: function (jqXHR, textStatus) {
},
});
Problem
The ajax call only gives me an error.
SO why is my testcall working but my ajax call not?
Attempts
I also tried a network analysis with the firefox debugging tools.
But I don't understand why it is not working because it shows "status-code 200" but the result is empty!?
This may or may not solve your issue, but if you're making cross-domain AJAX calls, make sure you set up your CORS:
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

Calling server side function from client side not working

Here page1ClientSideFn() is a client side function of Page.aspx. In this function I want to call the server side method page2ServerSideFn() of another page Page2.aspx.cs. Is there any problem with the below client side code? It's not working. Should I modify the ajax
function page1ClientSideFn() {
$.ajax({
type: "POST",
url: "Page2.aspx.cs/page2ServerSideFn",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
Error: function () {
alert("Error");
}
});
}
Your url looks wrong.It should not be page codebehind file.url: "Page2.aspx/page2ServerSideFn",
Also ensure page2ServerSideFn is public and static method.You can use chrome dev toolbar network tab to monitor your resquest you are sending.

Jquery ajax not calling server side function

I have solution structure as:
I want to call recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs from
CTL_RateRecommendationDetails.ascx
So i written code as:
$.ajax({
type: "POST",
url: "/UserControls/CTL_RateRecommendationDetails.ascx/recommendationProcess",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(value) {
alert(value.d);
},
error: function(e) {
alert("Ajax Error" + JSON.stringify(e));
}
});
But every time it comes in error block.
I have tried with :
url: "/CTL_RateRecommendationDetails.ascx/recommendationProcess",
And
url: "CTL_RateRecommendationDetails.ascx/recommendationProcess",
But its not calling function.
[System.Web.Services.WebMethod]
public static void recommendationProcess()
{
}
You can't call code behinds of user controls from JQuery Ajax
Ref : http://forums.asp.net/t/1423555.aspx
Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind
how-to-access-server-side-method-in-ascx-control-using-jquery-ajax-method

jquery ajax request with json throwing parsererror

I have searched lot of on this issue and tried almost everything but it doesn't seem to be work so posting it here.
I am trying to make jquery ajax call to ashx handler by passing json data. But my request doesnt reach till handler GetBalance.ashx
code :
var mydata = {};
$.ajax({
url: 'Handlers/GetBalance.ashx?type=authenticateRequest',
type: 'post',
dataType: 'json',
cache: false,
data: mydata,
success: function (data) {
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
in console it prints
parsererror
(empty string)
What i am doing wrong ? It should reach till .ashx before it gives any response parse error
Edit:
Changed as suggested by answer
Replace your line
data: mydata,
with
data: JSON.stringify(mydata),
contentType: "application/json",

Categories