The following code is working perfecting after publishing to my localhost. So I copied the files from my localhost and put them on the server. Now it's saying it cannot find the web method. The project is an MVC project and what's not working is an separate aspx page added to the project directory. So, I don't know if this has something to do with IIS. Any ideas would be greatly appreciated.
[WebMethod]
public static string LoadPatients(string phone, string user)
{
//SOME STUFF HERE THAT WAS EXCLUDED//
var sb = new StringBuilder();
for (var x = 0; x < Callerdt.Rows.Count; x++)
{
var addr = Callerdt.Rows[x]["Street"].ToString() + " " + Callerdt.Rows[x]["city"].ToString() + ", " + Callerdt.Rows[x]["State"].ToString() + " " + Callerdt.Rows[x]["ZipCode"].ToString();
sb.AppendFormat("<div class='tabs'><table>" +
"<tr><td class='title'><label>Name:</label></td><td>{0}</td></tr>" +
"<tr><td><label>DOB:</label></td><td>{1}</td></tr>" +
"<tr><td><label>Address:</label></td><td>{2}</td></tr>" +
"<tr><td><label>SSN:</label></td><td>{3}</td></tr>" +
"<tr><td><label>Z Number:</label></td><td>{4}</td></tr>" +
"</table></div><br/>", Callerdt.Rows[x]["Name"].ToString(), Callerdt.Rows[x]["DOB"].ToString(), addr, Callerdt.Rows[x]["SSN"].ToString(), Callerdt.Rows[x]["ZNUM"].ToString());
}
ret = sb.ToString();
return ret;
}
<script type="text/javascript">
$(document).ready(function () {
var p = document.getElementById('pn').value, u = document.getElementById('user').value, er = document.getElementById('error').value;
if (!(er == "true")) {
$("#loading").show();
$.ajax({
type: "POST",
url: 'CallerPopup.aspx/LoadPatients',
data: JSON.stringify({ phone: p, user: u }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#tabs').append(data.d);
},
complete: function () {
$("#loading").hide();
}
});
}
});
</script>
In my case, adding IgnoreRoute to RegisterRoutes() got me going. Now the aspx.cs "static" hosted [webmethod] loads ... url: 'LearnKO.aspx/FetchStudents',
aJax was throwing a 404 - Not Found on any page.aspx/webmethod call.
ie. the fix:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
I was setting up http://www.c-sharpcorner.com/UploadFile/1492b1/learning-knockout-part-1-introduction-to-knockout-js-and-cr/ in an MVC project instead of the recommended empty ASP.NET... my bad.
Related
I have a view with a button to call ajax but now need to include a parameter new { DNumber = item.DrawingNumber } and have that passed into the controller via ajax. What do I need to add to my code to make this work please?
view:
PDF
<script>
function OpenDrawingPDF() {
$.ajax({
url: "OpenDrawingPDF",
success: function () { alert("success"); }
});
return false;
}
</script>
Controller:
public void OpenDrawingPDF(string DNumber)
{
string Path = #"\\Serv1\Company\10 - Production\Production Drawings\CAD pdf\";
if (Directory.Exists(Path))
{
string Folder = DNumber.Substring(4, 2) + #"\";
System.Diagnostics.Process.Start(Path + Folder + DNumber + ".pdf");
}
}
Check the following approach. Provide your Id to your element holding a DBNumber and then access it from your function:
var dbNumber = $('#dbNumberItemId').val();
$.ajax({
url: "OpenDrawingPDF",
type: "Get", // I assume that you are sending get request
data: {
dbNumber: dbNumber
},
...
});
This was the solution that worked for me:
view:
<a id="myid" data-mydata1=#item.DrawingNumber href="javascript:" onclick="myPDF('tblCircuitDiagrams', this)">PDF</a>
<script>
function myPDF(table, value) {
var mydata = document.querySelector('#myid');
var dbNumber = value.dataset.mydata1;
$.ajax({
url: "OpenDrawingPDF",
data: { DNumber : dbNumber },
cache: false,
type: "GET"
});
}
</script>
controller:
public void OpenDrawingPDF(string DNumber)
{
string Path = #"\\serv1\Company\10 - Production\Production Drawings\CAD pdf\";
if (DNumber != null && Directory.Exists(Path))
{
string Folder = DNumber.Substring(4, 2) + #"\";
System.Diagnostics.Process.Start(Path + Folder + DNumber + ".pdf");
}
}
I have verified by using the browser debugger / network monitor that I am sending in a variable in an AJAX call called "search" and in the monitor it shows in the header as "search=test". I am trying to access this variable in the code behind but can't seem to find it? Here is my code for front and back-end, am I missing something?
Code Behind :
public class AJAXSearchLog : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string searchTerm = Convert.ToString(HttpContext.Current.Request.Form["search"]);
if(!string.IsNullOrEmpty(searchTerm)){
AspDotNetStorefrontCore.DB.ExecuteSQL("insert into TribSearch(SearchTerm,CustomerID,LocaleSetting) values(" + DB.SQuote(CommonLogic.Ellipses(searchTerm, 97, true)) + "," + '0' + "," + DB.SQuote("en-us") + ")");
}
context.Response.Clear();
context.Response.Write(searchTerm);
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
Front-End
window.onbeforeunload = function(e) {
if ($("#searchBox_text").val().length >= 2) {
var _search = $("#searchBox_text").val();
var url = "/AJAXSearchLog.ashx";
$.ajax({
async: false,
type: 'POST',
url: url,
data: {'search': _search},
contentType: 'application/json;',
dataType: 'json',
success: function(result) {
alert(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
};
I have found that the data wasn't getting passed through when the contentType was set to 'application/json'. Also, to read the POST variable, Request.Params[] was needed. Here are the 2 lines of code that I changed :
in the front-end -
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
in the back-end -
string searchTerm = Convert.ToString(context.Request.Params["search"]);
i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
I have a Web service WCF and I call the methods of my Wcf with Jquery ajax.
When I tested with a method without parameter, it works well.
But when I call a method with parameter, it doesn't work.
The problem is that in my success in $.ajax, msg is empty.
Here is my javaScript code :
function getStatistic3() {
var response;
var allstat3 = [];
var allyearstat3 = [];
var kla = $('#Select1').val();
kla = kla.replace("'", "\\'");
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52768/Service1/Statistic_3',
data: "klant='" + encodeURIComponent(kla) + "'",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
allyearstat3[0] = [response.Items[0].YearStart, response.Items[0].YearStart + 1, response.Items[0].YearStart + 2, response.Items[0].YearStart + 3, response.Items[0].YearStart + 4];
fillDataTable3(allstat3, allyearstat3);
if (bool3) {
$('thead tr th:eq(0)').replaceWith(function () {
return $("<td />").append($(this).contents());
});
$('thead th').attr('scope', 'col');
bool3 = false;
}
$('table').visualize({ type: 'line' });
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
}
I tested all with an .asmx Web service and all works well.
I have this error when I call the method :
TypeError: response.Items[0] is undefined
Msg is empty :
I think that I have a problem when I pass the parameter in ma $.ajax.
I seem to be having issues calling a WebMethod from jQuery, I am using this article as my starting point:
http://www.misfitgeek.com/2011/05/calling-web-service-page-methods-with-jquery/
JS
function WebMethod(fn, paramArray, successFn, errorFn)
{
//----------------------------------------------------------------------+
// Create list of parameters in the form: |
// {'paramName1':'paramValue1','paramName2':'paramValue2'} |
//----------------------------------------------------------------------+
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//----------------------------------------------------------------------+
// Call the WEB method |
//----------------------------------------------------------------------+
$.ajax({
type: 'POST',
url: 'ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: paramList,
dataType: 'json',
success: successFn,
error: errorFn
});
};
I am passing into this method like this:
$(".editableField").keydown(function(e) {
WebMethod('PriceContract',
[
'AQ', aq.val(),
'SOQ', soq.val()
], updateTextFields, failed);
});
C# (Note these are test methods, ignore the logic..)
[WebMethod]
public static ContractsListPricing PriceContract(string AQ, string SOQ)
{
ContractsListPricing clp = new ContractsListPricing();
// clp.Aq = nAQ * 2;
// clp.Soq = nSOQ * 2;
return clp;
}
When debugging the JS the paramList seems to be correct JSON (or so I believe):
{"AQ":"140000","SOQ":"1169"}
This is resulting in a parseerror and I'm unsure why.
Any help appreciated.
Thanks
Oh no, please never build JSON manually by using string manipulation as you did. That's absolutely horrible. Take a look at this article.
Here's the correct way:
function WebMethod(fn, paramArray, successFn, errorFn) {
var paramList = { };
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
paramList[paramArray[i]] = paramArray[i + 1];
}
}
$.ajax({
type: 'POST',
url: 'ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramList),
dataType: 'json',
success: successFn,
error: errorFn
});
}
Notice the usage of the JSON.stringify method to properly JSON encode the paramList object. This method is natively built into modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.