I can't seem to get this simple function working.
The AJAX call returns success but the function is never being called since the Debug.WriteLine is not showing up. The "Function has been called" alert does pop up. There are no errors in the Chrome console.
I am using ASP.NET Web Forms
The Contact.aspx.cs file:
public partial class Contact : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("Contact Page loaded");
}
[System.Web.Services.WebMethod]
public static string Test(string test)
{
Debug.WriteLine("Input param"+test);
return test;
}
}
In the Contact.aspx file
<button type="button" class="btn btn-info" onclick="ShowTest()">Test</button>
<script type = "text/javascript">
function ShowTest() {
//Tried this also (prefered)
//var res = PageMethods.Test("testMessage");
var testMsg = 'This is the test message';
$.ajax({
type: "POST",
url: "Contact.aspx/Test",
data: JSON.stringify({
test: testMsg
}),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('It worked! ' + result.d);
},
error: function (result) {
alert('Nope');
}
});
alert("Function has been called");
}
</script>
I have found the solution!
Authentication failed in call webmethod from jquery AJAX
Blockquote
I found the answer
Just comment below line in RouteConfig file
//settings.AutoRedirectMode = RedirectMode.Permanent;
Related
When trying to call an ASP.NET method from the client using $.ajax it gives the following error "Failed to load resource: the server responded with a status of 405 ()" knowing that the client and the API are both running on the same domain "localhost:4500", I followed the procedure I found in this Microsoft docs "https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-5.0 " and added the wwwroot folder to avoid the CORS issue but still can't call the API methods through the $.ajax method in javascript.
I tested the backend code through swagger and it was working just fine.
this my backend controller code:
[ApiController]
[Route("api/[Controller]")]
public class RunAnalysisController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok();
}
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody]RootObject ModelData)
{
try
{
ManageModel.CreateModel(ModelData);
return Ok(ModelData); //returning same object for testing purpose
}
catch
{
return BadRequest("Error");
}
}
}
and this my ajax function in the client side:
$.ajax({
type: "POST",
url: "api/RunAnalysis/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData()), //this class returns a json object
cache: false,
success: function (result) {
console.log(result);
},
error: function (ex) {
WriteToConsole(ex.responseText);
}
});
As mentioned in the comments, the issue relates the request url, change the url as below: url: "/api/RunAnalysis/LoadFramesData.
More detail information, you could refer the following sample:
Model:
public class RootObject
{
public int ID { get; set; }
public string Name { get; set; }
}
MVC View Page:
<input type="button" id="btnsubmit" value="Click Me" />
#section Scripts{
<script>
$(function () {
// LoadChart();
class RootData {
constructor(id, name) {
this.ID = id;
this.Name = name;
}
}
$("#btnsubmit").click(function () {
//var data = {};
//data.ID = "1001";
//data.Name = "Tom";
$.ajax({
type: "POST",
url: "/api/todo/LoadFramesData", ///// URL must be specified
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(new RootData(1001, "Tom")), //this class returns a json object
cache: false,
success: function (result) {
alert(result.name);
},
error: function (ex) {
alert(ex.responseText);
}
});
});
});
</script>
}
API upload method:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpPost("LoadFramesData")]
public IActionResult LoadFrameData([FromBody] RootObject ModelData)
{
try
{
return Ok(ModelData);
}
catch
{
return BadRequest("Error");
}
}
The result as below:
I am writing a javascript function for a button
<button type="button" class="btn btn-sm btn-outline-secondary" id="stopProcess" onclick="stopProcess(event, #queue.AgentQueueId, #queue.AgentId)" data-toggle="tooltip">Stop</button>
This is what my javascript function looks like
<script type="text/javascript">
$(document).ready(function () {
setInterval(function () {
reloadPage()
}, 50000);
});
function reloadPage() {
window.location.reload(true);
}
function stopProcess(e, agentQueueId, agentId) {
e.stopPropagation();
var data = JSON.stringify({ 'agentQueueId': agentQueueId, 'agentId': agentId });
$.ajax({
type: "POST",
url: "#Url.Action("StopTest", "Agents")",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
reloadPage();
},
error: function (data) {
$(".alert").text("Error completing the request.");
$(".alert").prop("hidden", false);
}
});
};
</script>
It correctly navigates to the function StopTest in my Agents controller but the parameters passed to it are null.
My controller code is
[HttpPost]
public bool StopTest(long agentQueueId, long agentId)
{
StopTestsResponse response = new StopTestsResponse();
try
{
response = _testAgentRepository.StopTest(new StopTestsRequest()
{
AgentId = agentId,
AgentQueueId = agentQueueId
});
}
catch (Exception ex)
{
throw ex;
}
return response.Success;
}
It would be of great help if anyone could point out where I am going wrong.
You should create a class with two properties:
public class Test
{
public long AgentQueueId { get; set; }
public long AgentId { get; set; }
}
And then in your controller you should have action signature like this:
public bool StopTest([FromBody]Test data)
You can see more about model binding in asp.net core here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1
Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.
I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms
I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.
I have the following JavaScript code:
appCode.runReports = function (e) {
var reportList = '';
$('.rptCheck:checked').each(function (index) {
reportList += ($(this).attr('reportName') + ',');
});
$.ajax({
url: '/Report/RunReports/?reports=' + reportList,
error: appCode.reportAjaxFailure,
success: appCode.listRunningReports,
complete: appCode.ajaxComplete,
dataType: 'json'
});
e.preventDefault();
}
$(document).ready(function () {
$('#runReportsButton').click(appCode.runReports);
});
The URL it calls into uses the following controller:
namespace workflowDemoMVC.Controllers
{
public class ReportController : Controller
{
public JsonResult RunReports(string reports = "")
{
try
{
var ret = reports.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return Json(ret, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ide.Trace.WriteLine(ex.ToString());
return Json(null, JsonRequestBehavior.AllowGet);
}
}
}
}
When I run the code in dev, the controller action executes as expected and returns, but none of the callbacks defined in the AJAX call (complete, error, or success) fire. Once, in an earlier code version, I saw an 500-coded exception (Internal Server Error,) but now I don't see anything at all.
Environment: MVC3, jQuery1.6 .net4
You should try and set the content type on the AJAX call. I had a problem like this and that fixed it for me. Basically you would do this. I know I had a lot of problems with IE until I specified this.
$.ajax({
url: '/Report/RunReports/?reports=' + reportList,
error: appCode.reportAjaxFailure,
success: appCode.listRunningReports,
complete: appCode.ajaxComplete,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});