Basic Simple Asp.net + jQuery + JSON example - c#

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;
}

Related

Posting Form values with jquery ajax call to inputstream in ASP.NET static method

Trying to use this code
i reached a dead end,
in the client side the form values collcected and serialized , but since it's not possible to use an instance of request in a static method
i failed to receive the seialized form values at the server,
i tried to bypass it by using the static HttpContext.Current.Request.InputStream
but i got empty stream.
how can i get the input stream in the server ?
client side :
function myFunction() {
$.ajax({
type: "POST",
url: "ajaxForm.aspx/Receiver",
contentType: "application/json; charset=utf-8",
data: $('#myForm').serialize(),
datatype : "json",
cache: false,
success: function (data) {
$('#result').html(data);
},
error: function (data) {
alert('failed');
}
});
}
server side first version (copied from that link):
{
string json;
using(var reader = new StreamReader(Request.InputStream)){
json = reader.ReadToEnd();
}
second version :
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver()
{
if (HttpContext.Current.Request.InputStream.Position != 0)
{
HttpContext.Current.Request.InputStream.Seek(0,System.IO.SeekOrigin.Begin);
}
byte[] data = new byte[HttpContext.Current.Request.InputStream.Length];
HttpContext.Current.Request.InputStream.Read(data, 0, data.Length);}
Currently your data doesn't look like JSON. Try like this.
var jsonData = JSON.stringify({
form: $('#myForm').serialize()
});
in the ajax call for data
...
contentType: "application/json; charset=utf-8",
data: jsonData,
datatype : "json",
...
Your method:
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver(string form)
{
//in the string form you should have myForm serialize.
}
If you want to use Context.Session for something, you need to enable it.
[System.Web.Services.WebMethod(EnableSession = true)]
This is an old post, but I recently ran into a similar issue with a client and figured I'd share my experience.
The client had a legacy app that was running jQuery 1.7.1 (were afraid to change this) and had recently set up a page to accept POST only. In jQuery 1.7.1 (and possibly others), I learned you have to pass the type (as well as the method?) for POSTs.
So, this
$.ajax({
url: {url...},
data: {data...},
method: 'POST',
...
});
became, this
$.ajax({
url: {url...},
data: {data...},
method: 'POST',
type: 'POST',
...
});
And everyone lived happily ever after.
Hopefully, this saves someone else some headache.

asmx round trip json

I am calling an asmx webservice which returns json (msg.d) that is consumed properly by knockout.js. When I attempt to return the identical json to asmx, I get error messages. Is there something obvious I'm missing? ... msg.d is a well formed object array.
calling storeGroupCategories(msg.d); returns webservice error ...
{"Message":"Invalid JSON primitive: Baby+Books."
calling storeGroupCategories(msg); returns webservice error ...
{"Message":"Invalid JSON primitive: d."
WebService
public class kbo_inexcludecategories : WebService
{
[WebMethod]
public List<Group> GetIncludeExcludeJson()
{
var Groups = new List<Group>();
ShopAssistGroupHandler.getInExCategories(Groups);
return Groups;
}
[WebMethod]
public GroupGuid StoreGroupCategories(List<InExCategory> inExCategories)
{
var inExString = JsonConvert.SerializeObject(inExCategories);
var returnGuid = DataHandler.SaveGroupJsonString(inExString);
return new GroupGuid(returnGuid);
}
}
Associated json ...
var _url = "kbo-inexcludecategories.asmx/";
var _method = "GetIncludeExcludeJson";
var _jsonData = "{}";
function storeGroupCategories(groupCategories) {
if(groupCategories != ""){
showProgressBar("Storing Group Categories");
getJsonData(_url, "StoreGroupCategories", groupCategories);
}
}
function getGroupMatrix() {
showProgressBar("Loading Group Categories");
getJsonData(_url, _method, _jsonData);
}
function getJsonData(url, method, jsonData) {
var myUrl = url + method;
$.ajax({
type: "POST",
url: myUrl,
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, //blocks window close
success: onSuccess,
error: onError
});
}
function onSuccess(msg) {
// Hide the fake progress indicator graphic.
hideProgressBar("");
if(msg.d.hasOwnProperty("Guid")) {
saveGroupGuid(msg.d);
}
else {
storeGroupCategories(msg.d);
//showGroupAccordion(msg.d);
//OpenAdvancedDialog();
}
}
json sample ...
"{\"groups\":[{\"__type\":\"group\",\"id\":1488,\"name\":\"Baby Books\",\"categories\":
[{\"__type\":\"groupcategory\",\"id\":152,\"name\":\"Activity Books\",\"value\":\"Included\"},
{\"__type\":\"groupcategory\",\"id\":167,\"name\":\"Bedtime and Dreams\",\"value\":\"Excluded\"}
To begin with I think you need to pass your json in like this:
storeGroupCategories(msg.d)
But within this function you also need to create valid json parameters to the post, which would look like this:
getJsonData(_url, "StoreGroupCategories", "{ inExCategories: " + groupCategories + " }");
I would also change your signature to the following, so groups matches the argument you are passing across:
public GroupGuid StoreGroupCategories(List<InExCategory> groups)
If you put a break point in the web page method, you will see exactly what is coming across, and check that it is what you are expecting.

Ajax call to use JSON data in UserControl.ascx

I have a usercontrol in a VisualWebPart project.I want to have an ajax call to get a json data and use it in a Jquery plugin.
in simple web applications I use a webservice that returns JSON data and call It in my pages via Ajax,that sounds like I cant use webservices and even Web Methods in my .ascx control,so how can I call a method in my UserControl to get JSON data.
EDIT: I have this code and I want to do this in a UserControl ,too.
in WebService:
public class getTimeLineService : System.Web.Services.WebService
{
[WebMethod]
public String getJsonTimeLine()
{
List<TimeLine> list = new List<TimeLine> { new TimeLine { headline = "Vine", text = "<p>Vine Test</p>", startDate = "1391,12,12", endDate = "1392,1,27" }, new TimeLine { headline = "Sh*t Politicians Say", text = "<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>", startDate = "1392,1,26", endDate = "1392,1,27" } };
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(list, sb);
return sb.ToString();
}
}
and consume this WebService by ajax:
$.ajax({
type: "POST",
url: "getTimeLineService.asmx/getJsonTimeLine",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonDate = eval( data.d );
},
failure: function (msg) {
alert(msg);
}
});
You can call a webmethod on the page and have the page's method pull from the server code. You could set a session value in the control and pull from that via your webmethod. As controls aren't pages, they're not actually serving anything, only being rendered.
As your using a static webmethod, you'll need to use HttpContext to get your session data.
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.session.aspx
Edit
Store your data from the user control in session:
Session["MyData"] = myDataObj;
You can access Session through your WebMethod this way:
var myRetrievedDataObj = HttpContext.Session["MyData"];
You can return serialized JSON from server objects and collections using the JavaScriptSerialzer class. http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
You then return that string to your AJAX call and you have your JSON data.

JSON return data is always null from WebService (C#.NET)

I have stepped through my WebServices code to validate that I am actually returning data, but when I check the return on the JSON side, it always says "null."
Here is a snippet of the WebService code.
UPDATED: To simplify things greatly, I'm returning a simple List from the web service instead of a custom object, and I've condensed the AJAX call as well.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetLocations(string CustomerID)
{
List<string> LocationsList = new List<string>();
string sql = "select customer_site from demand_addresses where customer_identifier=" + CustomerID;
if (gDB.ExecuteRet(sql, "DB"))
{
DataTable dt = gDB.GetResultDataSet(0);
int i = 0;
if (dt.Rows.Count > 0)
{
foreach (DataRow rs in dt.Rows)
{
LocationsList.Add(rs["customer_site"].ToString());
}
}
else
{
LocationsList.Add("No Data Found.");
}
return LocationsList;
}
else
{
LocationsList.Add("No Data Found.");
return LocationsList;
}
And here is the AJAX call (UPDATED to reflect Kami's comments below):
$.ajax({
type: "POST",
url: "/webservices/services.asmx/GetLocations",
data: "{ 'CustomerID': '" + selectedCustomer + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data.d); },
error: function (status) {alert(status);}
});
The "alert(data.d)" line results in "TypeError: data is null", and if I change it to "alert(data)" I simply get an alert box that says "null."
I need help understanding why the web service is properly returning data, but it's not making it back to AJAX/JSON.
You are not passing the variable to the OnSuccess function.
Also, I have had issues in the past where you need to use an anonymous function to call your subfunction.
Try something like this
$.ajax({
type: "POST",
url: "/webservices/services.asmx/GetLocations",
data: "{ 'CustomerID': '" + selectedCustomer + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, resp) { OnSuccess(data,resp)}, // anon function may be needed
error: function(data,resp) { OnError(data,resp)}
});
I was working on wcf webservice a days back and same was happening to me. At the final return statement everything was working fine. The data was there but when i saw it on the other side there was nothing.
The problem was custom object (in your case LOCATION) had a nullable property but was not defined as nullable. I did that and it started working. I am still not sure why but you should try it once.
public class Location
{
public string? customer_identifier { get; set; }
public string[]? customer_site { get; set; }
}

Complex type is getting null in a ApiController parameter

I don´t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.
public class ParametroFiltro
{
public string Codigo { get; set; }
public string Descricao { get; set; }
}
My ApiController Get method:
public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize)
My ajax call:
var fullUrl = "/api/" + self.Api;
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Filtro: { Codigo: '_1', Descricao: 'TESTE' }, page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
You are trying to send a complex object with GET method. The reason this is failing is that GET method can't have a body and all the values are being encoded into the URL. You can make this work by using [FromUri], but first you need to change your client side code:
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Codigo: '_1', Descricao: 'TESTE', page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
This way [FromUri] will be able to pick up your complex object properties directly from the URL if you change your action method like this:
public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize)
Your previous approach would rather work with POST method which can have a body (but you would still need to use JSON.stringify() to format body as JSON).
Provide the contentType property when you make the ajax call. Use JSON.stringify method to build the JSON data to post. change the type to POST and MVC Model binding will bind the posted data to your class object.
var filter = { "Filtro": { "Codigo": "_1", "Descricao": "TESTE" },
"page": "1", "pageSize": "10" };
$.ajax({
url: fullUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(filter),
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
It's also possible to access POST variables via a Newtonsoft.Json.Linq JObject.
For example, this POST:
$.ajax({
type: 'POST',
url: 'URL',
data: { 'Note': note, 'Story': story },
dataType: 'text',
success: function (data) { }
});
Can be accessed in an APIController like so:
public void Update([FromBody]JObject data)
{
var Note = (String)data["Note"];
var Story = (String)data["Story"];
}
If you append json data to query string, and parse it later in web api side. you can parse complex object too. It's useful rather than post json object, espeicaly in some special httpget requirement case.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
In .NET Core, the HttpClient sets the transfer-encoding: chunked header by default. This can cause the .NET Web API controller parameters to be null.
To get around this, you'll need to set the ContentLength header explicitly:
var json = JsonConvert.SerializeObject(myObject);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentLength = json.Length;
var response = await client.PostAsync("http://my-api.com", content);
SO answer if you already know the transfer-encoding header is the issue: How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient
Related bug which won't be fixed, which gives some insight into the problem: https://github.com/dotnet/runtime/issues/30283

Categories