I have a HTML page in my .Net project in that I have one script section
<script language="javascript" type="text/javascript">
s.property1="|*|property1|*|"
s.property2="|*|property2|*|"
<script>
In the c# code I'm reading the html file and replacing the "| * |property1| *|" values like below
StringBuilder siteCode = new StringBuilder();
//code to append html file to StringBuilder(siteCode)
if(xyz!=null)
{
siteCode.Replace("|*|property1|*|", xyz);
}
else
{
//remove s.property1="|*|property1|*|"
}
How can I remove s.property1="||property1||" from StringBuilder(siteCode)?
Just use the StringBuilder Replace method?
siteCode.Replace("s.property1=\"||property1||\"", "");
Related
In my app user writes some js code and i insert these code in the script tag and add them in the head tag of html.It was all working fine but when I use for loop in the js function it is getting some extra character after inserting in script tag inner HTML.
User-written function:
var el=element1.get();
var vectors=el.shapes;
var vectorCollection=[];
var correctVectors=[[2,3]];
var dotProducts=[];
for(var i=0;i<vectors.length;i++){
if(vectors[i].type<=5)
vectorCollection.push([vectors[i].startX,vectors[i].startY]);
}
for(var i=0;i<correctVectors.length;i++){
for(var j=0;j<vectorCollection.length;j++){
dotProducts.push(math.dot(correctVectors[i],vectorCollection[j]));
}
}
}
The insert function which user js code as src and insert in inner HTML of script tag:
public static void InsertScriptTag(HtmlDocument doc, string id, string src)
{
HtmlNode head = GetHead(doc);
HtmlNode element = doc.CreateElement("script");
element.SetAttributeValue("id", "autogeneratedcode");
element.SetAttributeValue("type", "text/javascript");
element.InnerHtml = src;
head.AppendChild(element);
}
I have debugged after passing src code to inner HTML it becomes like this:
When I try to pass my Html into WebBrowser.DocumentText which include JS.
<script src="jquery\script.js"> </script>
It is same path with my executable. But when open in Winform, it is unable to find the 'script.js'..
But when you enter the full path of script, it is working.
StreamReader stringReader = new StreamReader(htmlFilename, Encoding.Default);
StringBuilder sb = new StringBuilder();
string temp;
while (!String.IsNullOrEmpty(temp = stringReader.ReadLine()))
{
sb.AppendLine(temp);
}
stringReader.Close();
return sb.ToString();
Eventually I read html into StringBuilder, and pass it to WebBrowser.DocumentText. Any other way to make it works without giving full path of the script?
You can give like this into your HTML document
<script type="text/javascript" src="../jquery\script.js"></script>
in HTML Page
<html>
<head>
<script type="text/javascript" src={Fullpath}></script>
</head>
<body>
</body>
</html>
in C#
string ScriptfullPath = Application.StartupPath.ToString()+"\\jquery\\script.js";;
string htmlContent;
using (StreamReader reader = new StreamReader(Application.StartupPath + \\JQuery\\sample.htm"))
{
htmlContent = reader.ReadToEnd();
}
htmlContent = htmlContent.Replace("{Fullpath}", ScriptfullPath);
Then your HTML document will use Script file with full path...
Friends,
I am trying to use DyGraph in my application. Please look at the code below -
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
<title>crosshairs</title>
<script type="text/javascript" src="dygraph-combined.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.
Can anybody help me out to resolve this issue.
Thanks for sharing your valuable time.
You could define a controller action:
public ActionResult Data()
{
// Obviously this will be dynamically generated
var data = "alert('Hello World');";
return JavaScript(data);
}
and then:
<script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>
If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:
public class MyViewModel
{
... put required properties
}
a controller action which would populate this view model and pass it to the view:
public ActionResult Data()
{
MyViewModel model = ...
Response.ContentType = "application/javascript";
return PartialView(model);
}
and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);
Full Disclosure
This answer is copy/pasted from another question:
Dynamically generated Javascript, CSS in ASP.NET MVC
This answer is similar to other answers here.
This answer uses cshtml pages rather than ascx controls.
This answer offers a View-Only solution rather than a Controller-Only solution.
I don't think my answer is 'better' but I think it might be easier for some.
Dynamic CSS in a CSHTML File
I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:
/*<style type="text/css">/* */
CSS GOES HERE
#{return;}</style>
Dynamic JS in a CSHTML File
I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:
//<script type="text/javascript">
JAVASCRIPT GOES HERE
#{return;}</script>
MyDynamicCss.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
}
/*<style type="text/css">/* */
#foreach (var field in fieldList) {<text>
input[name="#field"]
, select[name="#field"]
{
background-color: #bbb;
color: #6f6f6f;
}
</text>}
#{return;}</style>
MyDynamicJavsScript.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);
}
//<script type="text/javascript">
$(document).ready(function () {
var fieldList = "#Html.Raw(fieldArray)";
var fieldArray = fieldList.split(',');
var arrayLength = fieldArray.length;
var selector = '';
for (var i = 0; i < arrayLength; i++) {
var field = fieldArray[i];
selector += (selector == '' ? '' : ',')
+ 'input[name="' + field + '"]'
+ ',select[name="' + field + '"]';
}
$(selector).attr('disabled', 'disabled');
$(selector).addClass('disabled');
});
#{return;}</script>
No Controller Required (using Views/Shared)
I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:
<style type="text/css">#Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">#Html.Partial("MyDynamicJavaScript")</script>
Using a Controller (optional)
If you prefer you may create a controller e.g.
<link rel="stylesheet" type="text/css" href="#Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="#Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
Here's what the controller might look like
MyDynamicCodeController.cs (optional)
[HttpGet]
public ActionResult MyDynamicCss()
{
Response.ContentType = "text/css";
return View();
}
[HttpGet]
public ActionResult MyDynamicJavaScript()
{
Response.ContentType = "application/javascript";
return View();
}
Notes
The controller version is not tested. I just typed that off the top of my head.
After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml #{return;}, but I haven't tried it. I imagine it's a matter of preference.
Concerning my entire answer, if you find any syntax errors or improvements please let me know.
I have a HTML page in which I have a button; pressing that button a javascript function is called - here results a String which is the representation of an xml. I want to represent this xml on the same page with the button, similar with what is in the picture below:!
Here is the simplified code I've tried but did not worked (see under the code the result of it - nothing displayed):
<html>
<head>
<script type="text/javascript">
function xml_test()
{
var xmlString = "<note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var my_div = document.getElementById("labelId");
alert(xmlString)
my_div.innerHTML += xmlString;
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="xml_test()"/>
<br><br>
<label id="labelId">XML: </label>
</body>
</html>
I've tried with an iframe also, but I do not have an file for the src attribute.
What I've tried is:
<html>
<head>
<script type="text/javascript">
function populateIframe() {
var xml = "<?xml version='1.0' encoding='UTF8' standalone='yes'?><note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var iframe = document.getElementById('myIframe');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open("text/xml"); // I know idoc.open(); exists but about idoc.open("text/xml"); I'm not sure if exists;
idoc.write('<textarea name="xml" rows="5" cols="60"></textarea>');
//idoc.write(xml); // doesn't work
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.close();
}
</script>
</head>
<body onload="populateIframe();">
<iframe id="myIframe" width="900" height="400"></iframe>
</body>
</html>
and the result is:
I've already looked over How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
I took some ideas from here
Thank you for helping me!
Just Create am HttpHandler, and open it in a Iframe:
public class Handler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
XmlSerializer serializer = new XmlSerializer(typeof(Note));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, new Note() { Name = "Kundan Sinha", Place = "Bangalore", State = "Karnataka" });
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
stream.Close();
writer.Close();
context.Response.ContentType = "text/xml;charset=utf-8";
context.Response.Write(utf.GetString(arr).Trim());
context.Response.Flush();
}
#endregion
}
public class Note
{
public string Name { get; set; }
public string Place { get; set; }
public string State { get; set; }
}
You can pass your received xml string to this where I am doing
context.Response.Write('Pass you XML data here');
You must use your favorite JavaScript library with a tree widget to display that XML in tree form.
Note that the "tree-like" view you see is actually IE's default view for XML files. Other browsers will have different views for XML files, and some do not even let you view XML files without a plug-in.
You should not depend on browser-specific functionality if viewing the XML in tree form is important to your page's functionality.
If you, however, just want to press a button and then the whole page gets turned into an XML, then by all means just redirect to that XML URI on button press. IE will show that XML file in tree form, while other browsers may either ask you to download the file, or display the XML file in whatever format that is determined by their plugin's.
I set the xml data in the src attribute:
iframeElement.setAttribute('src', 'data:text/xml,<test>data</test>');
Controller
public ActionResult GetCategories()
{
var htmlText = new StringBuilder();
var scriptText = new StringBuilder();
htmlText.Append("Hello world");
scriptText.AppendFormat("document.write({0});", htmlText.ToString());
var content = new ContentResult();
content.Content = scriptText.ToString();
return content;
}
View
<script src="/Home/GetCategories" type="text/javascript" language="javascript"/>
It runs well on FF, but not in IE.
A script tag needs a closing tag to be compliant. IE actually obeys the standard in this respect while FF is more forgiving. Change your view to:
<script src="/Home/GetCategories" type="text/javascript" language="javascript">
</script>