Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hi all
i create my c# web service, which get data from database sql, i create it to get data as JSON format, but on browser there are xml tag.
i found this code bellow to display as json directly. but how can i put my dataset into this code plz help

What I have tried:

C#
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
    public void HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";           
        HelloWorldData data = new HelloWorldData();
        data.Message = "HelloWorld";
        Context.Response.Write(js.Serialize(data));
    }
}

public class HelloWorldData
{
   public String Message;
}
Posted
Updated 1-Oct-19 4:11am
v2
Comments
sam9787 27-Sep-19 6:19am    
fill data adapter into dataset
F-ES Sitecore 27-Sep-19 4:56am    
The problem could your calling code. If you're using ajax make sure the content type is set to json and the datatype is too.
ZurdoDev 30-Sep-19 8:17am    
Google how to return a dataset in json format.

1 solution

Here is a working example of that
asmx syntax

HTML
<%@ WebService Language="C#" CodeBehind="TestService.asmx.cs" Class="WebApplication1.TestService" %>


C#
public class Course
{
	public int Id { get; set; }
	public string Name { get; set; }
	public int Marks{ get; set; }
}
 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class TestService : System.Web.Services.WebService
{
	[WebMethod]
	[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
	public void GetCourses()
	{
		var courses = new Course[]
		{
			new Course()
			{
				Id = 1,
				Name = "Course 1",
				Marks = 100
			},
			new Course()
			{
				Id = 2,
				Name = "Course 2",
				Marks = 100
			}
		};

		var js = new JavaScriptSerializer();
		Context.Response.Write(js.Serialize(courses));
	}
}


Result

[{"Id":1,"Name":"Course 1","Marks":100},{"Id":2,"Name":"Course 2","Marks":100}]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900