all,
I'm trying to pass html data up to a webservice that exists in .NET/c#. I'm using JQUERY but continue to get an error of "failed posted data". Is my syntax wrong in either my ajax script or in my code behind? Thanks for any help.
$(function () {
$("[id$=rdbSaveAjax]").click(function () {
var markedUPHTML = $("[id$=wrapper]").html();
var postData = "{'HTMLData' : '" + markedUPHTML + "'}";
$.ajax({
type: "POST",
url: "Role.asmx/test",
data: JSON.stringify({html: postData}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(JSON.stringify(postData));
}
});
});
});
webservice code behind:
/// <summary>
/// Summary description for Role
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Role : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string test(string html)
{
string strHTMLData = html;
return html;
}
}
var postData = "{'HTMLData' : '" + markedUPHTML + "'}";
This will not build a proper string if markedUPHTML has single or double quote in it. Use JavaScript escape method before concatenating. Try this
var postData = "{'HTMLData' : '" + escape(markedUPHTML) + "'}";
And then while passing the data you dont have to strigify it because its already a string. Just try this
data: { html: postData }
Try public static string on the server side, instead of public string
all,
I ended up finding the issue by using firebug. Everytime I tried posting back to connect to the test method in my Role.asmx file, I would get a 500 error. My solution is a Cassini project so I could not do much with configuring my local IIS site to change permissions.
Instead, I created a method in my code behind and placed [WebMethod] right above the method name. In my code behind I did not setup any declarations that you would typically see after adding a webservice file to your solution.
[WebMethod]
public static bool test(string strHTMLMarkup)
{
....code
}
I hope this helps anyone other there.
Thanks.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I tried this page method code in my ASPX page (ShowUsers.aspx), but the function gave me a 500 server error and does not go in to the success handler.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetInfo(string email)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
User user = UserService.GetUser(email);
return jss.Serialize(user);
}
And the JavaScript:
$(document).ready(function() {
$("#l").click(function() {
$("#modalUpdate").fadeIn(1000);
var url = "ShowUsers.aspx/GetInfo";
var email = "davidizhakinew#gmail.com";
$.ajax({
url: url,
type: "POST",
data: "{ email : " + email + " }",
dataType: "JSON",
contentType: "application/JSON; charset=utf-8",
success: function(msg) {
alert("success");
var data = JSON.parse(msg.d);
// do stuff (trimmed)
},
error: function(msg, xhr) {
alert(msg + ", " + xhr.responseText);
}
});
});
});
Can someone help me please?
Your JSON is invalid as you have not enclosed the email-address string inside quotes in JavaScript.
Programmatic proof that this will cause a server-side exception:
void Main()
{
string email = "davidizhakinew#gmail.com";
var postback = new Postback { email = email };
Console.WriteLine(new JavaScriptSerializer().Deserialize<Postback>("{ email : '" + email + "' }")); // email string escaped, ok
Console.WriteLine(new JavaScriptSerializer().Deserialize<Postback>("{ email : " + email + " }")); // YOUR INPUT, exception Invalid JSON primitive
}
public class Postback
{
public string email { get; set; }
}
A server-side exception manifests itself as an Internal Server Error, code 500. You should be able to see the exception details in the Windows event viewer.
So in JavaScript just wrap the email address inside quotes:
data: "{ email : '" + email + "' }",
Also note that all you need for your web method body is
public static User GetInfo(string email) {
return UserService.GetUser(email);
}
i.e. you do NOT need to spin up a serializer yourself. The Framework selects and spins up the necessary serializer (JSON or XML) based on the request headers.
AJAX call is returning status code 500. This is definitely an error on C# code, not JavaScript.
Status code 500 means Internal Server Error. ASP.NET applications throw that code when any exception occurs. Take a look in your logs / console output on C# side.
I suppose that the problem is in the method name. If not otherwise specified, due to ASP.NET naming conventions, your GetInfo is callable with GET method. You are calling this endpoint with POST, try to change that to GET.
Also, try other URL combinations, like:
ShowUsers/GetInfo
ShowUsers.aspx/Info
ShowUsers/Info
Create a new page and receive data from that page instead of receiving from the same page in asp.net
It is wrong to call
`"ShowUsers.aspx/GetInfo";`
try this with new page
`showUsersAjax.aspx'`
and make sure that your url should be like
var url = "http://www.doamin.com/ShowUsers.aspx/GetInfo";
try this
var url = "http://www.doamin.com/ShowUsers/GetInfo";
Assuming that ShowUsers is controller and GetInfo is the action
additionally, add POST signature in your API.
I am trying to call a method from my aspx page. This method is found on the aspx.cs page, but it is throwing an error. Do you know what's wrong, please?
ajax script
<script type="text/javascript">
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
} //Default.aspx
function insertMarker() {
var usernameName = 'username';
var usernameVal = document.getElementById('<%=hdnUsername.ClientID%>').value;
var latitudeName = 'latitudeStr';
var latitudeVal = document.getElementById('<%=hdnMarkerLatitude.ClientID%>').value;
var longituteName = 'longitudeStr';
var longitudeVal = document.getElementById('<%=hdnMarkerLongitude.ClientID%>').value;
var iconName = 'markerIcon';
var iconVal;
if (document.getElementById('blueMarker').checked) {
iconVal = 'images/blueMarker.png';
}
if (document.getElementById('greenMarker').checked) {
iconVal = 'images/greenMarker.png'
}
if (document.getElementById('pinkMarker').checked) {
iconVal = 'images/pinkMarker.png';
}
var titleName = 'name';
var titleVal = document.getElementById('<%=title.ClientID%>').value;
var descriptionName = 'description';
var descriptionVal = document.getElementById('<%=description.ClientID%>').value;
$.ajax({
type: "POST",
url: "mapping.aspx/insertNewMarker",
data: {"username" : usernameVal, "longitudeStr":longitudeVal, "latitudeStr" :latitudeVal, "markerIcon":iconVal, "name" : titleVal, "description" :descriptionVal},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Website Design
Save Marker
Title
Description
Save
Aspx.cs Method.
[ScriptService]
public partial class mapping: System.Web.UI.Page
{
[WebMethod]
private static void insertNewMarker(string username, string longitudeStr, string latitudeStr, string markerIcon, string name, string description)
{
//My Code
}
}
Your server-side webmethod cannot be private, you have to change it to public.
From MSDN documentation on webmethods:
When you create a Web service in managed code, you indicate the
methods that are available through that Web service by placing the
WebMethod attribute before the method declaration of a Public method.
Private methods cannot serve as the entry point for a Web service
although they can be in the same class and the Web service code can
call them.
Change your data like this
data:JSON.stringify({username : usernameVal, longitudeStr:longitudeVal, latitudeStr :latitudeVal, markerIcon:iconVal, name : titleVal, description :descriptionVal}),
You need to pass data as json stirng which has a specific format. If you use JSON.stringify data will be convetred to json string and if you don't use this than you have to pass every paremter and its value in quotes like this.
data:"{username:'" + usernameVal + "',............}",
My JSON is returning as an escaped string, I want the object without backslashes and outer quotes. I'm sure I'm missing a cast or something simple but I'll put the full code here to avoid misinterpretation.
I'm trying to get some data into a Infragistics Ignite UI grid via ajax/JSON/asmx web service. I've got data coming back, but it's not in the correct format. I'm not sure if the issue is in my ajax js or c# method return type (string), or the JSON serialisation?
Here's how I get call the web service using jquery ajax call:
var jqxhr = $.ajax(
{
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "/WebMethods/AssetWebService.asmx/GetAssets",
dataType: "json",
success: success,
error: function (xhr, msg) { alert(msg + '\n' + xhr.responseText); }
});
function success(msg) {
var entityColumns = getColumns();
var entityData = msg.d;
gridSetup(entityData, entityColumns);
}
function gridSetup(entityData, entityColumns) {
$("#assetGrid").igGrid(
{
autoGenerateColumns: false,
autoGenerateLayouts: false,
dataSource: entityData,
columns: entityColumns
}
);
}
Webservice c# code getting objects from entity framework:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AssetWebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAssets()
{
List<Asset> Assets = new List<Asset>();
using (var db = new CognyxMES())
{
Assets = db.Assets.ToList();
}
var results = from a
in Assets
select new
{
Id = a.Id,
Name = a.Name,
AssetTypeId = a.AssetTypeId
};
return results;
}
}
The JSON that I am getting returned looks like this when I debug in VS2013 (which causes my grid to not display any data):
"[{\"Id\":3,\"Name\":\"My Asset\",\"AssetTypeId\":1}]"
I want to it to look like this as my grid works when I hard code this in:
[{ "Id": 3, "Name": "My Asset", "AssetTypeId": 1 }]
I am new to JSON with c# so I know I could use string replace or similar to hack it into place but I'm after a more elegant fix and explanation of what I'm missing. Thanks
What you are returning IS a string and not JSON. That is your problem.
Your method should look like so. ASP.NET handles the rest for you.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public IEnumerable<object> GetAssets()
{
using (var db = new assetEntities())
{
var results = from a
in db.Assets
select new
{
Id = a.Id,
Name = a.Name,
AssetTypeId = a.AssetTypeId
};
return results;
}
}
Based on your jQuery request you have specified that you want JSON and yourResponseFormat = ResponseFormat.Jsonreturned` forces this... so your webservice will serialize the response to JSON for you. Easy-peasy. No manual serializing needed.
ResponseFormat = ResponseFormat.Json
You just told ASP.Net to convert your response to JSON.
Therefore, you should return a raw object, not a JSON string.
By returning a string, you're telling ASP.Net to serialize that string to JSON, which is not what you want.
I'm trying to learn how to make a simple call to the server from Javascript/jQuery. I've been trying to learn and could not find a tutorial with those simple steps.
I want to send a message to the server with two parameters (a DateTime and a String) and get back a DateTime. I want to do that via JSON.
How would the code in the server look like (structure only)?
Is there something special I should do on the server side? And how about security?
How would I implement the call in jQuery?
And how would I handle the result?
I'm most interested on code structure.
Update
I found the answer below great to get me started. However, I recently stumbled upon Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial. It's just a fantastic and very didactic step-by-step that I want to share with anyone else who comes across this question in the future.
There are several ways that you can do this; this will serve as a single example.
You could write something like this for your jQuery code:
urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function(data) {
setAutocompleteData(data.responseDateTime);
},
error: function(data, status, jqXHR) {
alert('There was an error.');
}
}); // end $.ajax
Next, you need to create a "generic handler" in your ASP.net project. In your generic handler, use Request.Form to read the values passed in as json. The code for your generic handler could look something like this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
string stringParam = (string)Request.Form["stringParam"];
// Your logic here
string json = "{ \"responseDateTime\": \"hello hello there!\" }";
context.Response.Write(json);
}
See how this work out. It will get you started!
Update: I posted this code at the CodeReview StackExchange: https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example
If you are using jQuery you could do it with a GET or POST.
$.get ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
$.post ('<url to the service>',
{ dateParam: date, stringParam: 'teststring' },
function(data) {
// your JSON is in data
}
);
Note that the name of the parameters in (e.g. dateParam, stringParam) need to be the same as the name of the parameters your service method is expecting. Also that your service will need to format the result as JSON, the data parameter in the call back will contain anything your service sends back (e.g. text, xml, json, etc).
See the jQuery documentation for $.ajax, $.get, $.post: http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.get/, http://api.jquery.com/jQuery.post/
Here sample code using jquery ajax call and on serverside webmethod returns jSon format data.
Jquery :
$(‘#myButton’).on(‘click’,function(){
var aData= [];
aData[0] = “2010”;
aData[0]=””
var jsonData = JSON.stringify({ aData:aData});
$.ajax({
type: "POST",
url: "Ajax_function/myfunction.asmx/getListOfCars", //getListOfCars is my webmethod
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response.d)) {
console.log(response.d)
}
function OnErrorCall(response)) { console.log(error); }
});
Codebehind : Here a webmethod which is returning json format data i.e list of cars
[webmethod]
public List<Cars> getListOfCars(list<string> aData)
{
SqlDataReader dr;
List<Cars> carList = new List<Cars>();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "spGetCars";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#makeYear", aData[0]);
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
string carname=dr[“carName”].toString();
string carrating=dr[“carRating”].toString();
string makingyear=dr[“carYear”].toString();
carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear});
}
}
}
}
return carList
}
//Created a class
Public class Cars {
public string carName;
public string carRating;
public string carYear;
}
I can call my webservice using jQuery IF the contentType = "application/x-www-form-urlencoded; charset=utf-8"
This will, however, return the xml: <string>[myjson]</string>
If I try to POST to the service using "application/json; charset=utf-8" I receive a 500 error with an empty StackTrace and ExceptionType. My webservice function is never hit so I'm not quite sure how to debug this situation.
My methods and classes are decorated with the appropriate attributes and are set to use JSON as their response type (as do my wsdl and disco files). I have the Ajax extensions installed and the required entries in web.config.
This is on a SharePoint farm, but I'm not sure that makes too much of a difference. I deployed the web.config changes on all WFE's as well as installed the ajax extensions. Again the service works, it just will not accept anything but the default content type.
Not sure what I'm missing here, fellas...
my ajax call:
$.ajax({
type: "POST",
url: "/_vti_bin/calendar.asmx/Test",
dataType: "json",
data: "{}",
contentType: "application/json; charset=UTF-8",
success: function(msg){
alert(msg);
},
error: function(xhr, msg){ alert(msg + '\n' + xhr.responseText); }
});
My webservice class:
[WebService(Namespace = "http://namespace")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class CalendarService : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test()
{
return "Hello World";
}
}
I have this working in 2.0 using web services, but I have put in place protection from the .d (see dataFilter below). I also am returning an array of objects. NOTE: the class for the object is static, or it would not work correctly for me at least.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ModifierCodesService.asmx/GetModifierList",
success: function(msg)
{
LoadModifiers(msg);
},
failure: function(msg)
{
$("#Result").text("Modifiers did not load");
}
});
Here is a snippett of my web service:
...
[WebService(Namespace = "http://mynamespace.com/ModifierCodesService/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class ModifierCodesService : System.Web.Services.WebService
{
/// <summary>
/// Get a list of Modifiers
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true)]
public Modifier[] GetModifierList()
{
return GetModifiers();
}
/// <summary>
/// Modifiers list from database
/// </summary>
/// <returns></returns>
private Modifier[] GetModifiers()
{
List<Modifier> modifier = new List<Modifier>();
ModifierCollection matchingModifiers = ModifierList.GetModifierList();
foreach (Modifier ModifierRow in matchingModifiers)
{
modifier.Add(new Modifier(ModifierRow.ModifierCode, ModifierRow.Description));
}
return modifier.ToArray();
}
}
...
the object code:
public static class ModifierList
{
/// <summary>
/// Returns the Modifier Collection.
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
public static ModifierCollection GetModifierList()
{
I have been fighting with this today with an iPhone app talking to a .Net Web Service.
I found that if I changed my Content Type to application/jsonrequest it went through without a problem and I was able to process the data in my web server.
Just for grins I added the line mentioned above to my web.config, but it did not make application/json work.
not sure if it could be this simple but I am using jQuery to call back JSON from my web methods.
the main difference I see is the attribute of the class
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://MyNameSpace")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Web : System.Web.Services.WebService{
[WebMethod]
public string TestMethod(){
return "Testing";
}
}
I have to assume you are using the 3.5 framework because that is the only way to expose JSON web methods.
My calls form jQuery look virtually identical, so no issue there.
If you're testing this in IE, try removing the charset declaration from your contentType attribute (i.e. it should look like this:
contentType: "application/json",
I have yet to discover why, but IE seems to get its knickers in a twist when making JSON calls with the "charset=UTF-8" part.
I think you're looking for the WebInvoke or WebGet Attribute, it lets you specify Uri Template, body style, request and responseformats, for example:
[WebGet(ResponseFormat= WebMessageFormat.Json)]
This Link may help. There's a similar article for WebInvoke (used mostly for post).
I use JQuery AJAX JSON calls to ASMX webservice quite a bit. It works perfectly in all browsers. I'm using .NET 2.0 with the ASP.NET AJAX Extensions installed (bundled in 3.5).
My class has the same decorators as your. My methods only have the [WebMethod(EnableSession = true)] decorator. My web.config however has the following entry in its httpHandlers section:
<add verb="*" path="*jsonservice.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
My jquery call looks as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "path/to/service/jsonservice.asmx/MethodName",
data: JSON.stringify(DTO),
dataType: "json",
success: function(rtrn) { alert("good"); },
error: function(req, msg, err) { alert("bad"); }
});
This article is the root of my knowledge.
Looks like you have to specify json as the response format in the scriptMethod tag. This is from vb.net, but I'm sure you get the idea:
ResponseFormat:=ResponseFormat.Json