I am pulling an XML template from the database and then using this template in my view (DYMO labels).
My issue is that when I use #Html.Raw, even with quotes around it, it only reads the first line as "Text" and after the line break reads the rest of the XML file as code on the page.
Picture below:
1
The first line appears fine, but starting with <DesktopLabel Version the XML is rendered as not plain text inside quotes.
Here is my current behind the scenes code:
var labelXml = '#Html.Raw(Model.XML)';
I need the entirety of the string stored in quotes ("", ''). Any help?
you need to encode the xml
#Html.Raw(Html.Encode(Model.XML))
I was able to resolve this issue using a JSON AJAX controller action call. Code and explanation below in case anyone ever needs help on this:
try {
var _size = "#Model.size";
$.ajax({
data: { size: _size},
type: "POST",
url: "/Unit/GetXMLFile/",
success: function (data) {
var labelD = dymo.label.framework.openLabelXml(data);
labelD.print(printerName);
},
error: function (response) {
alert("error" + response.responseText);
}
});
}
catch(err) {
alert("Couldn't load label");
return;
}
Because we are directly injecting the XML string into our DYMO framework we prevent any chance of encoding the <> characters as < and >.
I believe that the root issue came from attempting to transfer XML strings from Viewmodel > Javascript. Even attempting to store the XML in the viewmodel and store as plain text once inside the view did not work.
The only method that worked was the AJAX direct controller action that keeps XMLs format without any conversion.
Here is my controller action:
[HttpPost]
public JsonResult GetXMLFile(string size)
{
string XML = "";
if (size == "Small")
{
XML = db.UnitLabels.Where(x => x.Size == "Small").Select(x => x.LabelXML).FirstOrDefault();
}
else
{
XML = db.UnitLabels.Where(x => x.Size == "Large").Select(x => x.LabelXML).FirstOrDefault();
}
return Json(XML, JsonRequestBehavior.AllowGet);
}
Related
I have a question in using CryptoObfuscator or RedGate SmartAssembly to obfuscate Asp Mvc Assemblies :
It seems when you use one of these tools to obfuscate assemblies, then they will rename properties of classes, right?
so I think because of this operation we will lose access to some of the values in JSON format that would comes from server during serialization ( I mean that because of renaming the properties we cant parse JSON object in JS correctly)
If this is true, so how can we prevent loosing parseJSON operation in JS?
Let me include more details :
consider this class structure
public class MyClass
{
public string FName{get;set;}
. . .
}
//SampleController :
public JsonResult GetJson()
{
return Json(new MyClass{FName = "Alex"});
}
Now in ClientSide :
$.ajax({
url: "/Sample/GetJson",
context: document.body
}).success(function(data) {
//this is my problem : can I access to FName or Not?
var fname = jQuery.parseJSON(data).FName;
});
Basically Obfuscators DO NOT change return value's Property's names.
But if some obfuscator does so... you can Simply accomplish this by using following in your ajax call:
$.ajax({
url: "/Sample/GetJson",
dataType: "json"
success: function(data) {
var transformedData = {fname:arguments[0], somethingElse:arguments[1]};
//or
var fname = arguments[0];
//do the rest here...
}
});
You can also use [DoNotObfuscate] attribute in "smart assembly"
By using this, you can prevent json results from being obfuscated at all (on server side).
Also there should be some (other/same) strategies for other obfuscators.
I personally use CryptoObfuscator and it has some options to prevent (what/where) ever you'd like from being obfuscated.
I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.
I can successfully make a jQuery Ajax call into my C# Controller and receive back an XML string, but I need to in turn gather some Portfolio dates and package them up into a JSON object so I can send them back into another C# Controller.
If it's a C# issue, then I apologize if I'm in the wrong forum...however I'd like to pass my JSON object into the server side controller ..
Here's what I'm trying to do:
var nodeDatesJson = {"nodedates": // CREATE JSON OBJECT OF DATE STRINGS
{ "date": 01/20/2012,
"date": "01/21/2012" } };
getTradeContribs(thisPfId, nodeDatesJson.nodedates.date);
Now call the next js function:
function getTradeContribs(pfid, nodedates) {
//alert(nodedates);
$.ajax({ // GET TRADE CONTRIBS FROM SERVER !!
url: "/Portfolios/getTradeContribs?portfolioId=" + pfid + "&nodedates=" + nodedates,
type: "GET", // or "PUT"
dataType: "json",
async: true,
success: parseTradeContribs,
error: function (error) {
alert("failed in opening Trade Contribs file !!!");
}
});
}
function parseTradeContribs(data) {
alert("In parseTradeContribs..." );
$(data).find("Trade").each(function(){
$(".TradeContrib").append($(this).text());
})
}
and my C# controller is trying to read in the "nodedates" JSON object, but HOW do I read it in ?
public string getTradeContribs(string portfolioId, **string nodedates**)
{
// Build Portfolio Select request here !
RequestBuilder rzrRequest = new RequestBuilder();
// REQUEST FOR CONTRIBUTIONS !
// ... more code here..
xmlResponse.LoadXml(contribResponse);
string jsonTest = #" {""nodedates"": ""date"":""01/01/2012""}";
//return xmlResponse.OuterXml; // WORKS FINE
return "<Trade><TradeId>1234</TradeId></Trade>"; // RETURN TEST XML STR
}
thank you in advance...
Bob
The best way to receive a list of dates in a MVC action is to bind to a collection. What this means is that you should put your dates and other attributes in a form with the following naming convention:
<input type="hidden" name="dates" value="2012-1-20" />
<input type="hidden" name="dates" value="2012-1-21" />
Then you should serialize this form (look into jquery's docs for this) and post its data to your action, which will be something along the lines of:
public ActionResult getTradeContribs(string portfolioId, IList<DateTime> dates) {
// Do your work here
}
You should really take a look into MVC Model binding and collection binding as well:
Model binding to a list
Model binding objects
Also, if I may, your javascript object has two properties with the same name, which is probably not what you mean. If you want to have multiple dates stored somewhere in a object, you should use an array:
var nodeDatesJson = {"nodedates":
[ "01/20/2012", "01/21/2012" ] };
Sorry, but I didn't understand your doubt very well...but here it goes:
Maybe you should pass the json, well-formatted, as a string and use some C# parser.
This way you can get a object in server-side as same as the Json object in javascript.
=]
Currently, the following code works as intended but if I add an echo such as "LANG: en" anywhere in the code (let's say in the bootstrap), the following code won't work anymore and I get this ajax request response :
<br/>LANG : en{"response":true,"id":13}
(the ajax response contains the echo + json array ) and therefore I'm not able to print the id (it will print : undefined when i will try to access to data.id).
My question is : How can I print my debug info and still manage to perform ajax requests ?
Here is my code in the controller :
public function init()
{
$this->_helper->ajaxContext->addActionContext('retrievecategories', 'json')->initContext();
}
public function retrievecategoriesAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if (isset($_POST['id']))
$id = $_POST['id'];
$id+=1;
echo json_encode(array('response' => true, 'id' => $id));
}
}
My js code :
jQuery(function(){
var obj = {"id":12};
jQuery.ajax({
url: '/search/retrievecategories?json',
type: 'post',
data: obj,
dataType: 'json',
success: function(data){
var id = data.id;
alert(id);
},
error: function(data){
var id = data.id;
alert(id);
}
});
});
I hope I was clear enough. Thank you for your time !
If you echo anything but the JSON object, the JQuery parser will fail because the response is no longer a valid JSON. you could make a custom parser which interprets the response text and takes away the debug info leaving the JSON object, or you can include the debug info in the array you encode.
json_encode(array('data'=>'data','debug'=>'debug info'))
Then you detect if the debug field is present and after a console.log() or alert() you delete it form the object.
I would strongly recommend that you read about firePHP. It uses the same console that Firebug uses to display debug information from your php code. It is really simple to use with the Zend_Log.
EDIT: I've gotten the "famous question" badge with this question, so I figured I'd come back to it and stick what happened to me right at the very tippy top for people searching it to get an answer right away.
Basically, I was new to JSON. JSON is an object (obviously), as it contains all kinds of stuff! So I was like "Hey, javascript, just pop up an alert with all of this JSON data", expecting it to give me the JSON data as a string. But javascript doesn't do that (which is good!), so it was like "Hey, this is how we display objects, [object Object]".
What I could've done is something like alert(obj.DATA[0][1]) and it would've shown me that bit of the object.
What I really wanted was to verify that I was making good JSON data, which I could've checked with JSON.stringify.
Anyway, back to our regularly scheduled questions!
I'm trying to get some JSON data with an ajax call, but jQuery doesn't seem to like my JSON.
if I do something like:
function init2() {
alert("inside init2");
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
async: false,
success: function (data) {
alert(data);
var obj = jQuery.parseJSON(data);
alert(obj);
}
});
}
I get this as from alert(data):
{"COLUMNS":["MFIRST_NAME","MLAST_NAME","MMDDL_NAME","MEMPLY_ID","MAIM_NBR","EMPLY_ID"],
"DATA":[
["FNAME1 ","LNAME1 ","MI1 ","000-14-7189","026-0010","000-62-7276"]
,["FNAME2 ","LNAME2 ","MI2 ","000-01-2302","101-1850","000-14-7189"]
,["FNAME3 ","LNAME3 ","MI3 ","000-91-3619","102-1000","000-01-2302"]
,["FNAME4 ","LNAME4 ","MI4 ","000-25-9687","102-1000","000-91-3619"]
]}
which JSONLint says is valid json. alert(obj) gives me this, however:
[object Object]
adding dataType: "json" or "text json" just makes it report [object Object] at alert(data).
I'd really like to get this figured out, does anyone know why it's doing this? I'm pretty new at jQuery, my goal is to get an array for each of the columns. The same code I'm using has worked on a different page it looks like, which is what's bothering me the most.
The alert() function can only display a string of text. As its only parameter it takes a string or an object. The object will however be converted into a string that can be displayed.
When fetching JSON through jQuery, the $.ajax() method will automatically parse the JSON and turn it into a JavaScript object for you. Your data variable is therefor a JavaScript object, and not a JSON string as one might expect.
Since alert() only can display strings, when trying to alert your data object, your object will be turned into its string representation. The string representation of a JavaScript object is [object Object].
For debug-purposes you can use console.log(data) instead. You can then inspect the object and its content through the console in your browsers developer tools.
function init2() {
jQuery.ajax({
url: "/Mobile_ReportingChain.cfm",
type: "POST",
dataType: "json",
async: false,
success: function (data) {
console.log(data);
}
});
}
If you for some reason still want to alert the JSON-data, then you would have to turn your data object back into a JSON-string. To do that you can make use of JSON.stringify:
alert(JSON.stringify(data));
it wants a string
var obj = $.parseJSON(JSON.stringify(data));
try sending that object to console.log. You'll get a clearer picture what does it contain.
Also, put dataType: 'json' and remove parseJSON because it's all the same.
This is how it's supposed to work. Your JSON becomes a javascript object. You can then manipulate that object as a regular javascript object.
data.COLUMNS for instance should return an array.
[object Object] is the string representation of a javascript object.
Try accessing properties of the object.
alert(data.COLUMNS[0]);
jQuery.parseJSON will convert the json string into json object so alert(obj) will show you [object Object] since it is an object.
If you want to see what obj contains then use console.log(obj) and then check console log message.
$.getJSON( "UI/entidades.json.php", function(data){
result = JSON.stringify(data);
alert(result)
console.log(result)
})
(I knows this is an jquery problem; but just bear with me for a min. so that i can explain why this problem occurred to me in the first place).
I wanted to fill in the gaps made my deletion of records in my MySQL table ( primary key that was auto increment. So when records where deleted in between my id had missing keys. I though some mechanism to show those missing keys. So i created the code that created an array through a loop then deleted those keys that were present and echo backed that array (of course json_encode that array).
But to my amazement what ever I did it always end up giving me [object Object].
It baffled me a lot that were was the problem.
Solution: Just realigning the array and all my problem gone.
Below I would give an simplified example.
<!DOCTYPE html>
<html>
<head>
<script src="../js/jquery/jquery3.x/jquery-3.3.1.min.js"></script>
<title></title>
<script type="text/javascript">
$(function () {
$('#generate').click(function () {
$.get('tmp2.php?tab=1', function (data) {
var retStr = '<table>';
var par = $.parseJSON(data);
$(par).each(function () {
retStr += '<tr><td>' + this + '</td></tr>';
});
retStr += '</table>';
$('#res').html(retStr);
});
});
});
</script>
</head>
<body>
<input type="button" value="generate" id="generate" />
<div id="res"></div>
</body>
</html>
And the controller
<?php
if (!empty($_GET['tab'])) {
$ids = array();
for ($i = 0; $i < 50; $i++)
$ids[] = $i;
for ($i = 0; $i < 50; $i = $i + 2)
unset($ids[$i]);
// echo json_encode($ids); // this will generate [object Object]
$res = array();
foreach ($ids as $key => $value) {
$res[] = $value;
}
echo json_encode($res);
exit();
}
?>