Basic Simple ASP.NET + Jquery + JSON Example

Basic Simple Asp.net + jQuery + JSON example

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

get JSON object using jquery with ajax call from controller to view

Thanks for getting involved, after spending some time with your suggestions I managed to find a way to work around:

newObj.Add(bookSeat.Number.ToString());
newObj.Add(bookSeat.Result);

return Json(newObj.ToArray());

I am returning an array now and I access it in view as follows:

  $("#test").append(data1[1]);

Also, I analysed the data that is being received back, so I did the following:

$("#test").append(data1["result"]);

and now i get the expected string

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

The problem is your dataType and the format of your data parameter. I just tested this in a sandbox and the following works:

C#

    [HttpPost]
public string ConvertLogInfoToXml(string jsonOfLog)
{
return Convert.ToString(jsonOfLog);
}

javascript

<input type="button" onclick="test()"/>

<script type="text/javascript">

function test() {
data = { prop: 1, myArray: [1, "two", 3] };
//'data' is much more complicated in my real application
var jsonOfLog = JSON.stringify(data);

$.ajax({
type: 'POST',
dataType: 'text',
url: "Home/ConvertLogInfoToXml",
data: "jsonOfLog=" + jsonOfLog,
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},

processData: false,
async: false
});
}

</script>

Pay special attention to data, when sending text, you need to send a variable that matches the name of your parameter. It's not pretty, but it will get you your coveted unformatted string.

When running this, jsonOfLog looks like this in the server function:

    jsonOfLog   "{\"prop\":1,\"myArray\":[1,\"two\",3]}"    string

The HTTP POST header:

Key Value
Request POST /Home/ConvertLogInfoToXml HTTP/1.1
Accept text/plain, */*; q=0.01
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:50189/
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host localhost:50189
Content-Length 42
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Cookie EnableSSOUser=admin

The HTTP POST body:

jsonOfLog={"prop":1,"myArray":[1,"two",3]}

The response header:

Key Value
Cache-Control private
Content-Type text/html; charset=utf-8
Date Fri, 28 Jun 2013 18:49:24 GMT
Response HTTP/1.1 200 OK
Server Microsoft-IIS/8.0
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 4.0
X-Powered-By ASP.NET
X-SourceFiles =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?=

The response body:

{"prop":1,"myArray":[1,"two",3]}

Sending JSON object successfully to ASP.NET WebMethod, using jQuery

When using AJAX.NET I always make the input parameter just a plain old object and then use the javascript deserializer to covert it to whatever type I want. At least that way you can debug and see what type of object the web method in is recieving.

You need to convert your object to a string when using jQuery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/js/jquery.js" />
</Scripts>
</asp:ScriptManager>
<div></div>
</form>
</body>
</html>
<script type="text/javascript" language="javascript">
var items = [{ compId: "1", formId: "531" },
{ compId: "2", formId: "77" },
{ compId: "3", formId: "99" },
{ status: "2", statusId: "8" },
{ name: "Value", value: "myValue"}];

//Using Ajax.Net Method
PageMethods.SubmitItems(items,
function(response) { var results = response.d; },
function(msg) { alert(msg.d) },
null);

//using jQuery ajax Method
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "WebForm1.aspx/SubmitItems",
data: {"items":items.toString()}, // array to string fixes it *
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
jQuery.ajax(options);
</script>

And the Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomEquip
{
[ScriptService]
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]
public static void SubmitItems(object items)
{
//break point here
List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
}
}
}

Build Json string to tree view using jQuery and asp.net

var tree_design='text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 

nodeStructure: {
tree_design
}

when you link tree_design in nodeStructure it's in string format but nodeStructure expect in json format
either convert tree_design in json or do this way

var tree_design='{ name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; 

nodeStructure: {
text: tree_design
}

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model

public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

Controllers Like Below

    public ActionResult PersonTest()
{
return View();
}

[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/

/*Do something with object person*/

return Json(new {msg="Successfully added "+person.Name });
}

Javascript

<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}

$('#target').html('sending..');

$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>

Return Json object from Asp.net webMethod to Ajax call

Include using Newtonsoft.Json;

CS

public string CheckDetails(string param1, string param2)
{
var chk = new check
{
subject = "hello! " +param1 ,
description = param2 +" Years Old"
};
return JsonConvert.SerializeObject(chk);
}

public class check
{
public string subject { get; set; }
public string description { get; set; }
}

HTML

<div> 
<input type="text" name="name" id="txtname"/>
<input type="text" name="age" id="txtage"/>
<input type="button" id="btnSubmit" value="details"/>
</div>

Jquery

$(function () {
$('#btnSubmit').on('click', function () {
var options = {
type: "POST",
url: '/Ajax/CheckDetails/',
data: '{param1:"' + $('#txtname').val() + '",param2:"' + $('#txtage').val() + '"}',
async: false,
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
alert(typeof (data)); //it comes out to be string
//we need to parse it to JSON
data = $.parseJSON(data);
alert(data.subject);
alert(data.description);
}
}
};
$.ajax(options);
});
});


Related Topics



Leave a reply



Submit