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

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

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

C# create rest webservice

I created a Rest webservice in visual studio 2010 like this:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DocService
{
[WebInvoke(ResponseFormat = WebMessageFormat.Json,UriTemplate = "", BodyStyle = WebMessageBodyStyle.Wrapped)]
public data GetCollection(Stream streamdata)
{
}
}
User will send request with json data to this service:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
var jsonData = JSON.parse(JSONObject);
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
data: jsonData,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First problem: How can I access that json in my code?
For now I do like this (But json array can't serialize correct):
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
string resDecode = HttpUtility.UrlDecode(res);
NameValueCollection nvc = HttpUtility.ParseQueryString(resDecode);
var json = new JavaScriptSerializer().Serialize(
nvc.AllKeys.ToDictionary(k => k, k => nvc[k])
);
Output:
res = "pCode=123456789&mCode=001&tCode=&dArr%5B0%5D%5BdCode%5D=26&dArr%5B1%5D%5BdCode%5D=27&sId=sk"
resDecode= "pCode=123456789&mCode=001&tCode=&dArr[0][dCode]=26&dArr[1][dCode]=27&sId=sk"
nvc = {pCode=123456789&mCode=001&tCode=&dArr%5b0%5d%5bdCode%5d=26&dArr%5b1%5d%5bdCode%5d=27&sId=sk}
json = "{\"pCode\":\"123456789\",\"mCode\":\"001\",\"tCode\":\"\",\"dArr[0][dCode]\":\"26\",\"dArr[1][dCode]\":\"27\",\"sId\":\"sk\"}"
Second problem: In ajax, after request sent, it's always done with error and xhr.status and thrownError are 0 and null but with Fiddler I can see json output
Answer to the first problem:
Best way to use json in c# is to create a class with properties with exact name and type of the json object and then deserialize that json like this:
RequestClass reqParam = new RequestClass(); //Class with properties same as json object
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
JavaScriptSerializer js = new JavaScriptSerializer();
reqParam = js.Deserialize<RequestClass>(res);
Answer to the second problem:
My final javascript is like this and work fine:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
//Delete parse line
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
contentType: "application/json", //Added
data: JSONObject, // This line changed
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

Receive FormData as a single Key - Asp.NET MVC

I have a Patient like this in AngularJS
var Patient = {
PatientID : $scope.PatientID,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
Angular Controller
var pData = new FormData();
pData.append("model", Patient);
var getData = angularService.AddPatient(pData);
Angular Service
this.AddPatient = function (patientData) {
var response = $http({
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
method: "post",
url: "/Student/AddPatient",
data: patientData,
dataType: "json"
});
return response;
}
And my Method in MVC Controller
public String AddPatient() {
var model = Request.Form["model"];
// this giving me an object instead of JSON String
}
Please help me, how do i receive that Patient data, Read and save it in the database, and i dont want to use any loop, i mean like this
// I dont want to do this
var patientData = new FormData();
angular.forEach(Patient, function (value, key) {
patientData.append(key, value);
});

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

iterate through JSOn result

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;

Categories

Resources