How to use a JSON object created in code behind? - c#

In Info.aspx.cs i get a compressed file from the WebService. After decoding the content i have an xml File. Using XmlToJSON and JavaScriptSerializer the result is a JSON object. How can i use this object in Info.aspx?

Suppose your json is n below format
var A={
propertyOne: "propertyOne",
propertyTwo: "propertyTwo"
}
Use as below:
A.propertyOne
A.propertyTwo

Try this,
var returnValue = new Object();
returnValue.entityfirst = $("#entityfirst ").val();
returnValue.entitysecond = $("#entitysecond ").val();
returnValue.entitythird = $("#entitythird").val();
var request = $.ajax({
url: ..., //access method url
type: 'POST',
cache: false,
data: JSON.stringify(returnValue),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});

In you aspx page you have to use javascript if you do a dynamic load.
for example you call and recieve like this (jQuery) :
$.ajax({
url: "myUrlPageForCallJsonService",
type: 'POST',
data: "yourParamsForGettingJson"
dataType: 'json',
complete: function (results) { console.log('complete'); },
success: function (data) { //You logic in the success function
for (var i = 0; i < data.length; i++) {
console.log("success");
_html += '<li>'+ data[i].Param1 + '</li>';
}
_html += '</ul>';
$('#renderbody').html(_html);
},
fail: function (data) { console.log("fail"); }
});
Hope that's help

Related

ASP.NET C# Ajax Call Error

I'm going straight to the point here.
I'm trying to get the value pass from my ajax to controller and console.log the value. however, when I try to console.log the value it gives me error 500..
here's my code:
I've been doing ajax on php for a long time.. however, I'm still new to asp.net C# mvc so please bear with me.
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
CONTROLLER:
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
here's the error I don't know what's wrong with my controller though.
POST http://localhost:43969/Property/GetCities 500 (Internal Server
Error)
if using contentType: 'application/json; charset=utf-8' then use JSON.stringify to convert the data being sent to a JSON string.
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
As mentioned in the comments by #StephenMuecke
It does not need to be stringified if contentType: 'application/json; charset=utf-8', is removed (so that it uses the default application/x-www-form-urlencoded; charset=UTF-8').
you can add error function to check for possible error on your ajax.
Ex.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

Passing json object to webmethod via jquery ajax

I am trying to pass a json object to my .net webmethod.
Here is my C#:
[WebMethod]
public static string Guncelle(string personel)
{
return "It came.";
}
And my jquery ajax:
var saveData = {};
saveData.Isim = isim;
saveData.Soyad = soyisim;
saveData.Firma = firma;
.
.
.
var result = JSON.stringify({ personel: saveData });
$.ajax({
type: "POST",
url: "Personeller.aspx/Guncelle",
data: result,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
})
When I run code, it returns 'undefined' with alert. What is the correct way of passing json object to C# Webmethod ? I tried other examples for passing an object but none of them worked for me.
try this: data: "{personel:'" + saveData+ "'}"

Send file with ajax of jQuery to web service in C# (asmx)

I'm using web service with this method:
$.ajax({
type: 'POST',
url: 'page.asmx/method',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}'
});
Sending json string, and it works, but if I try to append with FormData the content of input and passing it in data value I have 500 response. What have I to do?
You need to serialize you data....
var data = new FormData();
var files = $("#YOURUPLOADCTRLID").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
});
And inside the controller you can have something like
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
Hope it helps...
You can send form object like : new FormData($(this)[0]) which send both input values and file object to the ajax call.
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'page.asmx/method',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
Send Client side value server side through jquery and ajax call.
Click On butto send value client side to server side
<script>
$(document).ready(function () {
$("#additembtn").click(function () {
jQuery.ajax({
url: '/TelePhone/Edit',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
Name: $('#txtUsername').val(),
Address: $('#txtAddress').val(),
},
error: function (request, status, error) {
},
sucess: function (data, status, request) {
}
})
});
});
</script>
// Web Servics Telephone.asmx
[HttpPost]
public ActionResult Edit(string data)
{
}

can not invoke webmethod to save handsonTable

I want to save handsontable data into json file,I have a javas cript method to get all data from handsontable as
$('button[name=save]').click(function () {
var str = handsontable.getData();
var value = JSON.stringify(str);
$.ajax({
url: "WebService.asmx/getData",
data: { 'data': value },
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function (res) {
if (res.result == 'ok') {
alert('Data saved');
}
else {
alert('Save error');
}
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
}
});
});
But I am not able to invoke WebService.asmx/getData(List data) .
public string getData(List<String> data)
{
return "";
}
What I need to pass in data:??...Please help.
data: { 'data': str },
dataType: 'json',
contentType: 'application/json',
With the contentType setting you are telling the server that you are sending JSON data, but you aren't. { 'data': str } is not a JSON string; it is a standard Javascript object literal. You are invoking the default jQuery behaviour for creating HTTP requests. This means you're sending a regular HTTP request, something like:
?data=thedata
To send actual JSON data, you need to call JSON.stringify:
data: JSON.stringify({ 'data': str }),
dataType: 'json',
contentType: 'application/json',
you must write before methode
[WebMethod]
and change parameters of method from List to string
then you can split it

jQuery.ajax "data" parameter syntax

I am trying to pass the contents of a javascript variable to the server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code:
(Client)
function expand(checkbox)
{
var selectedrow = checkbox.parentNode.parentNode;
var rowindex = selectedrow.rowIndex;
var parent = document.getElementById("parentTable");
var NextRow = parent.rows[rowindex + 1];
var cols = selectedrow.cells[1];
var ID = cols.firstElementChild.attributes.value;
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: "{sendData: ID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
NextRow.style.visibility = "visible";
}
(Server)
[WebMethod]
public static string childBind(string sendData)
{
return String.Format("Hello");
}
Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?
You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.
Try this
data: { sendData: ID }
You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: {sendData: ID},
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
You can also write this, if you want to send JSON:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: $.getJSON({sendData: ID}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) { alert("successful!" + result.d); }
})
Since you are using jQuery run these tests for the answer:
var ID = 45;
var x = "{sendData: ID}";
alert(jQuery.isPlainObject(x)); // false
var y = { sendData: ID};
alert(jQuery.isPlainObject(y)); // true
Here is the jsFiddle:
http://jsfiddle.net/3ugKE/
You are passing in 'ID' as a string rather than a variable.
All you need to do is remove the quotes around your data object.
Further reading on JSON and javascript objects:
http://www.json.org/
http://www.w3schools.com/js/js_objects.asp
you can use this code :
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: JSON.stringify({sendData: ID}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})

Categories