I have following method and i need to deserialize the retrieve stream.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val= JsonSteamToString(jsonString);
}
public string JsonSteamToString(Stream jsonStream)
{
StreamReader reader = new StreamReader(jsonStream);
return reader.ReadToEnd();
}
My class is as follows:
public class H2JsonStateObject
{
public string url { get; set; }
public string stateId { get; set; }
}
I'm calling this method using Ajax call as follows:
var value ="89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9";
var link="RedirectPage.aspx";
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
var jsonToSend = JSON.stringify(data);
$.ajax({
cache: false,
url: "StateRedirectService.svc/RefreshPagemethod",
type: "POST",
async: false,
data: jsonToSend,
success: function (data, textStatus, jqXHR) {
window.location.href = link;
},
error: function (xhr, status, error) {
alert('error');
}
});
When the request receive to web method and after converting the value it get following string.
"\"{\\\"url\\\":\\\"RedirectPage.aspx\\\",\\\"stateId\\\":\\\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\\\"}\""
Now i need to deserialize url & stateId. How can i do that?
I tried followings. but couldn't able to deserialize.
Using DataContractJsonSerializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(val)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(H2JsonStateObject));
H2JsonStateObject p2 = (H2JsonStateObject)deserializer.ReadObject(ms);
}
It throws exception and says :
Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''.
Using JavaScriptSerializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Object obj = serializer.DeserializeObject(val);
This gives me my object as string value as follows:
"{\"url\":\"RedirectPage.aspx\",\"stateId\":\"89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9\"}"
What I did wrong and how can i get RedirectPage.aspx and 89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9 value?
Able to solve this problem in following way. my problem is with Json string value.
public void RedirectHyperlink(System.IO.Stream jsonString)
{
string val = JsonSteamToString(jsonString);
string JsonVal = val.Replace("\"", "'");
var json_serializer = new JavaScriptSerializer();
H2JsonStateObject myobj = json_serializer.Deserialize<H2JsonStateObject>(JsonVal);
H2RequestRedirect.RedirectToTemp(myobj.url, myobj.stateId);
}
in here string needs to be in following format.
JsonVal = "{'url': 'RedirectPage.aspx','stateId': '89aafdec-0a9e-4d05-b04e-1ca4bf8cfeb9' }";
When i'm calling this method i send json object without JSON.stringify(data);
var data = '{"url":"' + link + '","stateId":"' + value + '"}';
$.ajax({
cache: false,
url: "StateRedirectService.svc/RedirectHyperlink",
type: "POST",
async: false,
data: data,
success: function (data, textStatus, jqXHR) {
//alert('OK');
window.location.href = link; },
error: function (xhr, status, error) {
alert('error');
}
});
Then it works as a charm...
Related
I was trying to get the base64 post in my codebehind webmethod,
but it seems like everytime I include the base64 I get an error : the server responded with a status of 500 (Internal Server Error) - it keeps on hitting the error function.
The Post works with the other strings when the base64 is not inlcuded int the data that im passing.
function event_create() {
alert("alert test : function works => onclick");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var eventTitle = $("#eventTitle").val();
var eventDesc = $("#eventDesc").val();
var eventTimeStart = $("#eventTimeStart").val();
var eventTimeEnd = $("#eventTimeEnd").val();
var eventDateStart = $("#eventDateStart").val();
var eventDateEnd = $("#eventDateEnd").val();
var eventType = $("#eventType").val();
var eventPlace = $("#eventPlace").val();
var eventAttendee = document.getElementById("lblSelected").innerText;
var userID = sessionStorage.getItem("userID");
var imageBase64 = getBase64(document.getElementById('test').files[0]);
var data = { 'eventTitle': eventTitle, 'eventDesc': eventDesc, 'eventPlace': eventPlace, 'eventType': eventType, 'eventAttendee': eventAttendee, 'userID': userID, 'imageBase64': imageBase64};
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: ".../../../../Operation/insert.aspx/createEvent",
data: JSON.stringify(data),
datatype: "json",
success: function (result) {
if (result.d <= 0) {
//false alert something
alert("FALSE");
}
else if (result.d > 0) {
//true
alert(result.d);
}
else {
alert("sent but no call-back");
}
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" connection to the server failed ");
console.log("error: " + errorthrown);
}
});
}
Here's the Webmethod that will get the post
[WebMethod(EnableSession = true)]
public static string createEvent(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string userID, string imageBase64)
{
String orgID = (String)HttpContext.Current.Session["orgID"];
string response = orgID;
string path = HttpContext.Current.Server.MapPath("~/Users/Organizer/organizerData/"); // de path
//Check if directory exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "event1" + ".jpg";// for instance
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
File.WriteAllBytes(imgPath, imageBytes); //write the file in the directory
return imageBase64;
}
my project is an MVC Web application I am using ajax call to get a huge list of data as JSON.
Here is the code( i am not sure what I a missing ):
$.ajax({
url: url, //server
type: "POST",
async: true,
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
jQuery.each(data, function (i, val) {
//Success code
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
window.baseShowModalOkCancel("<p>Backlog Data</p>", "<p>Error in Database</p>", "ERROR");
}
});
}
Action Controller:( This is a post method in return statement I can see the list of object with the data.
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetBacklogWithData(string id)
{
using (var db = new LiensTrackerEntities())
{
List<BackLogDataList> backLogData = new List<BackLogDataList>();
List<BackLogData> backLog;
backLog = db.BackLogDatas.OrderBy(x =>x.CaseNumber).ToList();
foreach (var item in backLog)
{
BackLogDataList backLogDataList = new BackLogDataList
{
FileNo = item.FileNo,
BackLogId = item.BackLogID,
FirstName = item.FirstName,
LastName = item.LastName,
Middle = item.Middle,
Suffix = item.Suffix,
Address = item.Address,
Address2 = item.Address2,
City = item.City,
St = item.ST,
Zip = item.SP1ZIP,
AmaesRecordCreatedDate = item.AMAESRecordCreatedDate != null ? item.AMAESRecordCreatedDate.ToString().Split(' ')[0] : null,
AddedInRecipient = item.AddedInRecipient
};
backLogData.Add(backLogDataList);
}
}
return Json(backLogData, JsonRequestBehavior.AllowGet);
}
}
It returns with 200 ok but execute the error function when i look into console i found the following error:
Thee error is due to max json string length. the solution is
MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer
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);
}
});
I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}
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