Javascript does not accept HTML String from MVC? - html

Javascript does not accept HTML String from MVC?
My MVC contoller from where I am sending the HTML template in string from txt file
using (StreamReader sr = new StreamReader(#"D:\Templates\NewGridTemplate.txt"))
{
// Read the stream to a string, and write the string to the console.
obj.sGridTemplate = sr.ReadToEnd().Replace(Environment.NewLine, " ");
//Console.WriteLine(line);
}
return View(obj);
Actual code in csHTMl Javascript
var sHTML=$(#Model.sGridTemplate);
Below is screen shot for error . HTML string is not accepted by Javascript. shows character "<" etc.. Please help let me know what I missed.Image 3

You need to put your content within quotes so that it becomes a Javascript string, otherwise it'll be interpreted as syntax and you get the error because it's not valid JS syntax
var sHTML=$('#Model.sGridTemplate');
And the problematic line in the resulting client-side code should look more like this:
var sHTML=$(' < ...
... than:
var sHTML=$( < ...

Related

parse model data to JSON object

I need to convert a list of model objects into a JSON list.
<a data-model="#Model.Schools"></a>");
The list of schools is parsed to a jquery eventhandler when the above button is pressed (I left some code out here)
Here, I naturally want to read the list of schools to a json list.
var items = JSON.stringify(button.data('model'))
var items2 = JSON.parse('"' + button.data('model') + '"')
I tried the above, however without any luck, it still yells at me for trying to convert a System.Collections.Generic.List`1.
Also I tried to serialize the object to JSON at the button, i.e. #HTML.raw(Json.Serialize(Model.Schools) but it just gives me an empty object in my jQuery...
Therefore, how do I convert a Model object to a json object in jQuery?
If I get your problem statement correctly, it seems you are pretty much there.
you need to serialise your list into Razor attribute (don't use #Html.Raw helper as it will not escape your string and mess with your page):
Full .net framework
<a id="btnModel" data-model="#Json.Encode(Model.Schools)" onclick="process()">TEST</a>
<!-- assuming you have Newtonsoft.Json package installed, the following line should also work-->
<a id="btnModel" data-model="#Newtonsoft.Json.JsonConvert.SerializeObject(Model.Schools)" onclick="process()">TEST</a>
and then in your Javascript:
function process() {
var m = $('#btnModel').data('model');
alert(JSON.stringify(m));
}
check out this dotnet fiddle for working example
.net core 3
Apparently the built-in serilizer somehow garbles the formatting so it needs proper html encoding. This unfortunately will mean you have to decode it in Javascript. One way to avoid this hassle would be to output your json string into javasctipt block (see second example)
<a id="btnModel" data-model="#Html.Encode(Json.Serialize(Model.Schools))" onclick="process()">Method 1 - Lotsa pain</a>
<a id="btnModel1" onclick="process1()">Method 2 - Less back and forth</a>
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
function process() {
var a = $('#btnModel').data('model');
a = JSON.parse(decodeHtml(a));
alert(JSON.stringify(a));
}
function process1() {
var a = #Json.Serialize(Model.Schools);
alert(JSON.stringify(a));
}

Ambiguous format output in nodejs

I am having output in following format as
"[{"a":"a1"},{"a":"a2"}]"
I want to actually extract it in array of json:
[
{
"a":"a1"
},
{
"a":"a2"
}
]
How to convert it?
You have tagged this with Node-RED - so my answer assumes that is the environment you are working in.
If you are passing a message to the Debug node and that is what you see in the Debug sidebar, that indicates your msg.payload is a String with the contents of [{"a":"a1"},{"a":"a2"}] - the Debug sidebar doesn't escape quotes when displaying strings like that.
So you likely already have exactly what you want - it just depends what you want to do with it next.
If you want to access the contents you need to parse it to a JavaScript Object. You can do this by passing your message through a JSON node.
Assuming your input contains the double quotes in the beginning and end, it is not possible to directly JSON.parse() the string.
In your case, you need to remove the first and last character (the double quotes) from your string before parsing it.
const unformattedString = '"[{"a":"a1"},{"a":"a2"}]"'
const formattedString = unformattedString.substr(1, unformattedString.length - 2)
const json = JSON.parse(formattedString)
The variable json now contains your JSON object.
I would suggest a different method which will get your work done without using any third party library.
var a = '[{"a":"a1"},{"a":"a2"}]';
var b = JSON.parse(a);
console.log(b); // b will return [{"a":"a1"},{"a":"a2"}]
Another way which is eval function which is generally not recommended
var d = eval(a);
If you want to use JQuery instead use :
var c = $.parseJSON(a);

Get JSON page content with PhantomJS

I would like to know how to parse JSON in phantomjs. Any page content is enclosed in html (<html><body><pre>{JSON string}</pre></body></html>). Is there an options to remove enclosing tags or asking for a different Content-Type as "application/json"? If not, what's the best way to parse it. Is it using jQuery after including with includeJS jQuery?
Since you are using PhantomJS which is built of the webkit browser you have access to the native JSON library. There is no need to use page.evaluate, you can just use the plainText property on the page object.
http://phantomjs.org/api/webpage/property/plain-text.html
var page = require('webpage').create();
page.open('http://somejsonpage.com', function () {
var jsonSource = page.plainText;
var resultObject = JSON.parse(jsonSource);
phantom.exit();
});
Here is what I did:
var obj = page.evaluate(function() {
return eval('(' + document.body.innerText + ')');
}
Then the obj you got is the JSON object returned from that page.
As already in the accepted answer, I would suggest using JSON.parse() for converting a JSON string into an object.
For example, your code could look like this:
var jsonObject = page.evaluate(function() {
return JSON.parse(page.plainText);
});
If the json data contains html strings, they will be removed within the suggested page.plainText attribute.

How can I pass json string into HtmlHelper's result?

I want to pass a serialized json object and returned it within custom Html Helper's result. Something like this
public static HtmlString SomeHelper(this HTMLHelper htmlHelper)
{
var MyObject = new Foo();
var oSerializer = new JavaScriptSerializer();
var str = string.Format(#"<a href""#""
onclick=""var myObject = $.parseJSON(0);
alert('my object name property '+ myObject.Name); ""> Click me</a>",
oSerializer.Serialize(MyObject));
return new HtmlString(str);
}
That thing theoretically should work, but it doesn't. It puts serialized string to markup and then everything gets messy, because of double and single quotes. I tried to apply HtmlString after serialization, I even tried to use HTmlString.ToHtmlString(). Nothing works.
In fact I probably shouldn't do that. The click event call should be used unobtrusively. I know. Then I still have to save json object somewhere in the resulting markup.
Upd: I even tried to do that:
sJson.replace("\"",""")
Not helping. Browser automatically converts "s into ". I don't know how to preserve the markup
Is html.Encode the answer?
return new HtmlString(Html.Encode(str));
I guess the only solution would be to replace all double quotes in oSerializer.Serialize(MyObject)) with some other symbol, which wouldn't conflict in html markup, and then before the parsing put double quotes back, otherwise it wouldn't be a legit json string.

Replacing string in html dynamically in Android

I am using "loadDataWithBaseUrl(...)" to load a html file, stored in assets, to Webview. that contains a string "Loading..." and a rotating GIF. String "Loading..." is hard coded, and it'll not be localized. How to replace that string dynamically, so that it can be localized?
Please help me to resolve this.
There are various solutions I could think of :
Load a different asset file according to the current language (get the current language using Locale.getDefault()), This way you can translate your HTML files independently.
Use place holders in your HTML file (for instance #loading_message#), then load the asset file in a String, replace all the occurences of the placeholder by the appropriate localised message (String.replaceAll("#loading_message#", getText(R.string.loading_message).toString())), finally load the processed HTML into the WebView using the loadData(String data, String mimeType, String encoding) function.
To load the asset file, you can do something like that:
File f = new File("file:///android_asset/my_file.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String eachLine = br.readLine();
while(eachLine != null) {
sb.append(eachLine);
sb.append("\n");
eachLine = br.readLine();
}
// sb.toString is your HTML file as a String
I had a similar problem when using the WebView to show help text that should be translated.
My solution was to add multiple translated HTML files in assets and loading them with:
webView.loadUrl("file:///android_asset/" + getResources().getString(R.string.help_file));
For more details go to: Language specific HTML Help in Android
String str = "Loading ..."
String newStr = str.substring("Loading ".length());
newStr = context.getResourceById(R.string.loading) + newStr;
I hope the code is sufficiently clear to understand the idea: extract the string without "Loading " and concatenate it with the localized version of "Loading" string