My current project has a .js file with hard coded data in it. So I am referencing this file and on clientside. I am using this file to get the data when ever I require on client side. But my task is to generate this .js file dynamically. I am getting my values in json format from database. SO I need a way to write this json formatted data into .js file, so I can use that written data on client side.
Needed Format in JS:
var list = new Array();
list["1000"] = "TestEvent1";
Actual Json Format:
{
"__metadata": {
"type": "event_Result"
}, "event_id": 1000, "event_GROUPId": 17, "event_name": "TestEvent1",
}
Please help me.
Thanks
You can have a generic handler ashx that outputs javascript content. Set your output content type to "text-javascript".
It doesn't have to have a file extension of .js, the content type and how it's reference is what matters
<script type="text/javascript" src="myJavascript.ashx"></script>
Why don't you simply use the json encoded data by saving it into a variable or by overriding the variable that holds the initial data?
Related
So, I have been running into all kinds of CORS errors (when using HTTPS) and Not allowed to load local resource: file:///C:/Windows/TEMP/e3ef26_75603_4.xml when saving my file to a temp folder and then trying to serve the request via AJAX to be displayed on my browser.
Basically the scenario is that I am requesting a file from a S3 bucket. Now there are couple of things that I tried:
By directly giving the full file path (HTTPS) with associated bucket and file name to a AJAX call. This is done by first generating the file path on the Controller method and assigning a ViewBag variable. Something like:
ViewBag.currentURL = JsonConvert.SerializeObject(tempfilepath);
And associated AJAX:
$(function executeXML() {
//console.log('#Html.Raw(ViewBag.currentURL)');
$("#myeditor").execute({
ajaxOptions: {
pathtoxml: #Html.Raw(ViewBag.currentURL)
},
});
});
This method works quite well when the S3 bucket has public access and the CORS policies are there for the bucket.
Problem: Using this method on a S3 bucket that has no public access and no CORS policies will result in the No 'Access-Control-Allow-Origin' header is present on the requested resource from any browser.
Sigh! But not yet,
The second method that I was trying to do is to read the file on the server side and save it to a XML document. Now when I want to save this XML document, I use a temp folder to save my file. Something like this:
using (WebClient client = new WebClient())
{
string myXMLString = client.DownloadString(fullpathstory);
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXMLString); // suppose that myXmlString contains "<Names>...</Names>"
//Now save the file to temp folder
tempfilepath = Path.Combine(Path.GetTempPath(), filename);
xml.Save(tempfilepath);
}
This gives me a path like: file:///C:/Windows/TEMP/e3ef26_75603_4.xml
Now when I am sending this path to my AJAX, it gives me the error jquery.min.js:4 Not allowed to load local resource: file:///C:/Windows/TEMP/e3ef26_75603_4.xml which is quite obvious and expected.
Question: I am looking for a way to save my XML document in-memory and generate a path or a stream that can be read by my AJAX call and serve it on the browser.
Is there such a way or do I need to create a proper file sever where I store all my generated XML files and then read from that location. It would basically be a temp server folder but then I would need to keep monitoring the ever increasing size of it.
Thanks in advance
Rather than pre generating the file, i would recommend to generate file on demand. The moment user issues an ajax request for file, file would be generated in memory, converted to byte array, returned to client (as a base64 encoded string) and download would start at client's end.
SimpleJSON link https://github.com/Bunny83/SimpleJSON
There is no documentation and I am trying to understand how to (add/delete/edit) information into the JSON file below.
All Values are strings
I want to know how to Add JSON Object/Array like shown below to the file
Delete a whole object/array ex:("Character0":{...})
edit a Node x["Character0"]["Head"].Value = "New Head" so that value updates
Any help would be awesome if you know how the SimpleJson class works would be helpful.
JSON FILE
{
"Character0":{
"Head":"HeadCube",
"Neck":"NeckCube",
"Body":"BodyCube",
"Arms":"Sphere_Capsule_Arms",
"Legs":"Sphere_Capsule_Legs"
}
}
Basiclly I'm trying to create an HTML, I already have it written but I want the user to be able to put some text on the textboxes and saving it into strings and use later when creating the HTML file.
I tried playing abit with StreamWriter but I don't think that will be the best idea.
Also I want it to open on the default web browser , or just on IE if it's easier after the file is created.
I really need help as I'm struggling especially with the creating part.
Thanks for reading!
You can also do this without external libraries.
Set up your HTML file as follows:
<!DOCTYPE html>
<html>
<header>
<title>{MY_TITLE}</title>
</header>
<body></body>
</html>
Then edit and save the HTML from C#:
const string fileName = "Foobar.html";
//Read HTML from file
var content = File.ReadAllText(fileName);
//Replace all values in the HTML
content = content.Replace("{MY_TITLE}", titleTextBox.Text);
//Write new HTML string to file
File.WriteAllText(fileName, content);
//Show it in the default application for handling .html files
Process.Start(fileName);
If you already have the HTML you want to export (just not customized), you could manually add format strings to it (like {0}, {1}, {2}) where you want to substitute text from your app, then embed it as a resource, load it in at runtime, substitute the TextBox text using string.Format, and finally write it out again. This is admittedly a really fragile way to do it, as you need to make sure the number of parameters agrees between the resource file and your call to string.Format. In fact, this is a horrible way to do it. Actually, you should do it the way #EmilePels suggests, which is basically a less fragile version of this answer.
I am currently reading an image from an SQL Server database as byte[]. I would like to pass the image either as a byte[] or a real image to jQuery and dynamically load it.
How and what would be the best approach to do this?
Thanks in advance. :)
Edit: Here's the solution:
Server-side / C#:
string json = JsonConvert.SerializeObject(employee);
Client-side / Ajax:
$('#image').attr('src', "data:image/jpg;base64,"+employee.Image);
Return the byte[] from the webserver with the correct content-type set, that way you should be able to set it as a source for a image tag. Should be the simplest solution.
If you must do it this way, you can insert image data directly into the src attribute using the following syntax:
data:image/<type>;base64,<data>
Replace with the image type (jpg, png, gif) and with your data, encoded in base 64.
However, as decyclone says, the best way to do this would be to create a separate page that only outputs your image data, and sends the appropriate content-type header. Then set the image src to point to that page.
I don't think using jQuery is the right thing to do here. It's a client side thing. JavaScript, to be specific.
Usually, you create a page that writes all these bytes in array using Response.Write() and setting the content-type to jpeg, bmp, etc. depending on image type.
I am currently reading an image from a JSON Response. I would like to pass this encoded string into the image control on Jquery template and load it dynamically, How and what would be the best approach to do this? Template is as follows:
<script id="ImageDiv" type="image/png">
<div style="width:200px;height:150px;>
<img src="${ImageView}" alt="" />
</div>
</script>
Js file is as follows:
var demo = new Object();
$.each(msg.images, function (key, value)
{
if (this.IsImage)
{
demo["ImageView"]="data:image/png;base64,"+this.Image;
$('#ImageDiv').tmpl(demo).appendTo("#Demo-Image");
}
});
JSON Response is as follows:
msg = {"Images":[ "Description": "Image1", "Image": "encoded string of image", "IsImage": true, "MimeType": "image/png", } ]
less space to copy encoded string of image.
I have a long javascript in a string and programatically using RegisterClientScriptBlock, I add it to my page.
Is there any way to have the intellisense detect my javascript inside the string?
Code:
string Script0 =
#"
function dummy()
{
}
var PTRValues = new Array();
...
...
..
";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myCustomScriptBlock", Script0, true);
No, you can't get intellisense inside the JS string. The IDE doesn't know this particular string is JS.
If it's long don't put it in the *.cs file. Instead store it in a *.js. If you really want you can load the file into memory at runtime and serve it embedded in the html instead of referenced.
Unfortunately, this is not possible.
The best solution is to make put the code separate .js file, then write the following:
Page.ClientScript.RegisterClientScriptBlock(
GetType(),
"myCustomScriptBlock",
File.ReadAllText(myJSFilePath),
true
);
For optimal performance, you should read it only once, then store in in the cache.
Ok, these guys are getting close...
Don't EVER embed scripts in code. Always embed as resource or for prototyping and develepment use ClientScript to render a <script/> tag and reference a .js file.
There are just too many reasons wny you would not want to embed script in code to list. google it.
What you are after is to render some javascript from the codebehind via ClientScript and you would like design time intellisense support?
Ok,
To get intellisense you will need a .js of some kind. The approach I suggest, to promote maintainability and prevent dupe scripts that can get out of sync is:
create an EMPTY file called myScript.js.
create another script containing your code named myScript-vsdoc.js
mark myScript-vsdoc.js as embedded resource and serve it as and embedded web resource
meanwhile, back in the IDE, add a script tag pointing to myScript.js, which is an EMPTY file
press SHIFT-CTRL-J and bingo, you have intellisense for your embedded script, your embedded script is in a source file that is editable and discoverable and you have no duplication.
That is how i do it.