iterate through JSOn result - c#

I have a WebMethod being called from ajax, trying to iterate through the returned data. The data being returned is "{ BusinessTypeID = 2 }". I'm trying to figure out how to just get the value 2?
//Function called from ajax
[System.Web.Services.WebMethod]
public static string[] GetTerminalBusinessTypes(string terminalID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<string> results = new List<string>();
try
{
var terminalBusinessTypes = (from bt in db.BusinessTypes
join obt in db.OxygenateBlenderBusinessTypes on bt.BusinessTypeID equals obt.BusinessTypeID
where obt.OxygenateBlenderID == Convert.ToInt32(terminalID)
select new
{
bt.BusinessTypeID
}).ToList();
for (int i = 0; i < terminalBusinessTypes.Count(); i++)
{
results.Add(terminalBusinessTypes[i].ToString());
}
}
catch (Exception ex)
{
}
return results.ToArray();
}
The ajax function:
function PopulateTerminalBusinessTypes(terminalID) {
$.ajax({
type: "POST",
url: "OxygenateBlenderCertificationApplication.aspx/GetTerminalBusinessTypes",
data: "{'terminalID':" + terminalID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var targetValue = data.d;
var items = $('#cblTerminalBusinessType input:checkbox');
$.each(targetValue, function (key, targetValue) {
alert(data[index].BusinessTypeID);
});
}
})//end ajax
}

When your web service returns the json value, asp.net wraps in an object, with the key being d and the value being your json string. Review this link for more info.
You have to parse the value string into a json object. Using jQuery (v1.4.1 or higher):
jQuery.parseJSON(targetValue);

To be honest I cannot see where your "index" is defined.
Shouldn't the alert line read
$each(targetVale, function(key, item) {
// on second look, this wont work as you are converting toString()
alert(targetValue[key].BusinessTypeId)
// this should
alert(item)
});
You could also throw a debugger; line above the alert and see the values being traversed.

You may want to try returning a JSON string from C#:
public static **string** GetTerminalBusinessTypes(string terminalID)
...
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(results);
return sJSON;

Related

ASP.Net Core - Store and Retrieve FormCollection in SQL Server database

I have a razor form that collects a long list of inputs from the user. I need to store the data in SQL Server. But I don't want to create that many columns in the SQL Server table. So my idea was to have a column FormData of type nvarchar(max), convert the FormCollection object to Json and store it in table.FormData.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
string json = JsonConvert.SerializeObject(collection);
MyObject form = new MyObject()
{
id = 1,
formdata = json
};
repository.Add(form);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
Storing the data works fine, but when I retrieve it, the deserialization fails.
I wrote an API to retrieve it. The return data has escape characters, and I believe that's what is causing the issue.
FormData:
[
{
"id": 1,
"formdata": "[{\"Key\":\"Name\",\"Value\":[\"Person1\"]},{\"Key\":\"EmpID\",\"Value\":[\"12345\"]},{\"Key\":\"inputDepartment\",\"Value\":[\"\"]},{\"Key\":\"inputLocation\",\"Value\":[\"\"]},{\"Key\":\"inputSupervisor\",\"Value\":[\"\"]},{\"Key\":\"inputExitDate\",\"Value\":[\"\"]},{\"Key\":\"optShouldEmailBeActive\",\"Value\":[\"on\"]},{\"Key\":\"optWhoHasAccess\",\"Value\":[\"on\"]},{\"Key\":\"__RequestVerificationToken\",\"Value\":[\"CfDJ8M9krkWO1eBMp3rh5qzs-Rv1bj07MLUgOrWTcXV-ivrIiXkHW30I0e0NYWuBtbvyjONlULoENzivw1NXfITYL1Y8CVIOoDgFW_ACPu9XLhHe8x5KUcOZ-FuLeXyR-Vj0Q7RE_lSmnDchZsB6ihVyW4bnFcKAjo9X62rknPNUHvvEjsIN7-1EHtrgMT2-TgLPkQ\"]}]",
}
]
I couldn't find a way to avoid having those escape characters when serializing.
I thought of using .replace() to remove these escape characters before storing, but I'm not sure if it's a good idea. I may end up doing that if I can't find a better solution.
============================
Deserialization Code:
Just for testing I tried deserializing right after serializing, and it fails.
Ajax Call Result of JSON.stringify(data):
Javascript Code:
Tried removing escape characters.
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
alert(json);
var obj = JSON.parse(json);
var a = "";
$.each(obj, function (index) {
a += obj[index].Key + "\n";
});
alert(a);
},
error: function (data) {
}
});
}
After removing escape characters, alert(json):
Error in Chrome Developer Console:
This error is at JSON.parse(json);
=============================================
Update:
After fixing the javascript code, it works:
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
var obj = JSON.parse(json);
obj = obj[0].formdata;
$.each(obj, function (index) {
var o = obj[index];
$("#" + o.Key).val(o.Value);
});
},
error: function (data) {
}
});
}
Removed the escape characters, it fixed the issue.
These lines did the trick in the following javascript getData() method.
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
Javascript:
function getData() {
var url = baseURL + "api/itexit";
$.ajax({
url: url,
type: "GET",
success: function (data) {
var json = JSON.stringify(data);
json = json.replace(/\\"/g, '"');
json = json.replace('\"[', '[');
json = json.replace(']\"', ']');
var obj = JSON.parse(json);
obj = obj[0].formdata;
$.each(obj, function (index) {
var o = obj[index];
$("#" + o.Key).val(o.Value);
});
},
error: function (data) {
}
});
}

How to decode date and get date in correct format in ajax success?

Hello Friends I am getting not error but some issue in getting date in ajax success so tell me how can i correct this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {},
url: "edit-registration.aspx/GetUserInfo",
datatype: 'json',
success: function (data) {
var objData = eval("(" + data.d + ")");
var rows = objData.Table1.length - 1;
$("#disabilityCertIssueDate").val(objData.Table1[0][15]);
},
error: function (e, v) {
alert('there is some error');
}
});
Data are return in json from abc.aspx.cs page
public static string DataSetToJSON(DataSet ds)
{
try
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
catch (Exception e)
{
return e.Message;
}
}
I am getting correct date format on cs page but in success i am getting /Date(787170600000)/ this so how can i retrieve in correct format and set to html5 date control
Format date before passing to JS as string - It would be valid value for html5 input.
Example:
DateTime.Now.ToString("yyyy-dd-MM");
javascript date specification

Passing value to the controller as a parameter through ajax call

View
function editEmployee(val) {
var a = ko.toJSON(val);
// alert("Hi");
$.ajax({
url: "#Url.Action("editEmployee", "Registration")",
contentType: "application/json; charset=utf-8",
type: "POST", dataType: "json",
data:a,
success: function (data) {
// alert("awa");
debugger;
DisplayUI.getEmpArray(data);
var abc = DisplayUI.getEmpArray();
}
});
}
Controller
[HttpPost]
public JsonResult editEmployee(string ID)
{
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//dynamic item = serializer.Deserialize<object>(ID);
var employee = from s in db.Employee
select s;
try
{
if (!String.IsNullOrEmpty(ID))
{
employee = employee.Where(s => s.empId.Contains(ID));
}
}
catch (Exception ex)
{
}
var val = Json(employee.Select(s => new { s.empId, s.firstName, s.lastName, s.mobilePhn, s.email, s.desigId }).ToList());
return val;
}
Through ajax call I'm passing the value into controller as a string variable(ID). But that value is not passing it is visible as null value. I want to know get the value as a parameter what i should do.
Check whether you are getting json object
var a = ko.toJSON(val); // here you should check whether you are getting json object
Only if you get json object,the value will be bind to the controller.
put alert like this
var a = ko.toJSON(val);
alert(a);
if it is json object it will show like this
[object],[object]

Javascript and C# Handler - AJAX with JSON, sending array

When I send an array with AJAX (using JSON), my C# handler does not know how to handle the whole query (suddenly the querystrings combine with each other for some reason).
In this example I'm sending a very simple array to the server and the server says the querystring Name is null (but it is not null); Sending any request without the array works fine.
On that note, would appreciate if anyone could explain what the array looks like on the URL (if I wanted to send a request through the browser for example).
AJAX code:
function btnClick() {
var arr = new Array();
arr[0] = "Hey";
arr[1] = "Stackoverflow";
arr[2] = "What's your name?";
var jsonParam = { Name: "test", Pass: "123", Stuff: arr }
$.ajax({
url: "Test.ashx",
type: "get",
data: JSON.stringify(jsonParam),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async:false,
success: function (response) {
alert(response.Name);
}
});
}
Handler code:
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
string res = jss.Serialize(new UserInfo { Name = context.Request.QueryString["Name"], Pass = "pass" + context.Request.QueryString["Pass"], Stuff = new string[] { "1", "2" } });
context.Response.Write(res);
}
You cannot get the json from querystring.
You can use this; You should install NewtonJsonfor JSonConvert from nuget. If you don't want that, you can use JavaScriptSerializer instead of that.
protected object FromJsonToObject(Type t)
{
Context.Request.InputStream.Position = 0;
string json;
using (var reader = new StreamReader(Context.Request.InputStream))
{
json = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject(json, t);
}

jquery ajax not returning data on success c# asp.net

I cant for the life of me figure out why my data being returned is empty. In fiddler i see the json
d=[{"response":[{"h":"h1"},{"h":"h1"}] }]
in fiddler there is a 200 status on the row where i see the json, but no other rows after that one ( maybe its not returning? ). This is the code i am using
$('.SomeLink').click(function () {
var sfn = $('#ID1').val();
var sfp = $('#ID2').val();
var sfi = $('#ID3').val();
var gid = $('#ID4').val();
$.ajax({
type: "POST",
cache: false,
url: '/AjaxHandler.aspx/GetNewHtml',
contentType: "application/json; charset=utf-8",
data: "{'a':'" + sfn + "','b':'" + sfp + "','c':'" + gid + "','d':'" + sfi + "'}",
dataType: "json",
success: function (data) {
alert(data.response[0].h); //acts like a syntax error/no alert box
alert(data); // [object Object]
alert(data.response); // undefined
alert(data.response.count); //acts like a syntax error/no alert box
},
error: function (e) {
alert("Error: " + e.responseText);
}
});
});
AjaxHandler.aspx
[System.Web.Services.WebMethod()]
public static string GetNewHtml(string a, string b, string c, string d)
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "h1"},
new Samp{h = "h1"}
};
return Serialize(new { response = samp });
}
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
Samp Class
public class Samp
{
public string h = "";
}
This is my first time using jquery ajax with asp.net so im sure im missing something that is probably relatively simple. Im using .Net 4.0 , jquery 1.7.1 , iis 7.5
Try data.d for your return object:
alert(data.d);
its tripping over the quotes around the property names. try string indexes.
try
data["response"][0]["h"]
returns h1

Categories

Resources