Convert model to array mvc 3 - javascript

I got a model what i want is by clicking on a button to run a javascript function which will convert that model into array and send it to a controller that will read and parse the data as json or just as a Model.
example:
[View]:
#model MyApp.MyModel
<input type="button" value="Send" onclick="SendData()" />
function SendData()
{
var data = "#Model" // this is where im stuck maybe $.makeArray("#Model") ?
$.ajax({
url: 'getData',
type: 'POST',
data: $.toJSON(data),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result);
}
});
}

Json.Encode Method could help you
Converts a data object to a string that is in the JavaScript Object Notation (JSON) format.
And your code
var data = #Json.Encode(Model);

Just wanted to add to the answer by #archil.
It may be better to use #Html.Raw(Json.Encode(Model)), depending on your requirements, instead of just Json.Encode(Model) because the json object will be properly encoded.
Example Json data using #Html.Raw(Json.Encode(Model))
[{"id":1,"name":"Joe"}]
Example Json data using Json.Encode(Model)
[{"id":1,"name":"Joe"}]

Related

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

How to use JSON data from wcf url in javascript

I am trying to receive the JSON data from the WCF service url in javascript.
I used the following javascript code.
$(function(){
$("input:button").click(function() {
$.ajax({
dataType: 'json',
type: "GET",
url: "http://192.168.1.109/EIM/EIS.svc/json/getLatestLocation/Mobile/Mobile/1001",
success: function (data) {
var innerHtml = "";
document.getElementById('test').innerHTML=data;
//'test' is ID of <div>
document.getElementById('testlab').innerHTML=data.getLatestLocationResult.status.code;
//'testlab' is ID of <label>
$("#test").html(innerHtml);
alert("JSON DATA");
alert(data.getLatestLocationResult.status.code);
}
});
});
});
JSON data from url is:
{"getLatestLocationResult":{"status":{"code":"00","description":"Request
OK"},"reason":{"code":"000","description":"Request
OK"},"PersonDetails":{"PersonName":"Santosh Kumar
Sahu","PersonNumber":"1001","Identification":"Pan
Card","IdentificationNumber":"P567","ContactNo":"987654","Gender":"Male"},"location":[{"dateandtime":"7\/17\/2013
10:45:20 AM","latitude":"19.0469536","longitude":"72.9112502","address":"ND","city":"ND","state":"ND","country":"ND"}]}}
Please give me a suggestion to use receive this data.
Thank you.
You should eval the data - otherwise it's just a string.
obj = eval('(' + data + ')');
Now you can use obj as a rightful JS object and access it's members.
Here is the fiddle which evaluates your data string and accesses the resulting object members http://jsfiddle.net/M4BK5/

dynamically add an array by using jQuery ajax call

In the most of the websites when I see the browser 'view page source', a lot of java-script array or JSON data is populated dynamically. I think this data we can get it from the database and store it in java-script array. Can any one suggest me how to add data dynamically from jQuery ajax call and assign it in array variable..
I tried with array push() method. but no luck.
Can any one suggest me how to do it?
You can do it as follows:
$.ajax({
type: "GET",
url: // Your URL,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var result = data.d; // your json data
$.each(result , function (index, value) {
myArray.push([value.property, value.property2]); // push array note `[]`
});
}
});

How to navigate JSON Object in jQuery?

I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)

Categories