I'm using some javascript/jquery in an asp.net mvc view and I'm appending some html code using a html helper.
$("#update").append('#Html.CustomHelper(m => m.Values)');
The custom html helper generates a block of html a few lines long. The problem is the first line starts with a ' and then the last line ends with a ', but the rest of the lines aren't string.
Is there a way in JavaScript or jQuery to stringify the block of HTML?
Better approach would be to encode the string for Javascript on the ASP.NET side.
Use maybe:
HttpUtility.JavaScriptStringEncode(string)
This way you are guaranteed to have a consistent and valid encoding without worrying about quotes etc.. Just substitute your string in the method.
You could have your CustomHelper method return a properly JS-Encoded encoded string. Right before you return from your method call, you could use HttpUtility.JavaScriptStringEncode(yourStringHere).
You could use Html.Raw
$("#update").append("#Html.Raw(Html.CustomHelper(m => m.Values))");
Why not to use double quotes?
$("#update").append("#Html.CustomHelper(m => m.Values)");
Related
This might be simple and stupid question. But, I'm playing with an API and it returned me the following URL structure:
"https:\/\/s3.ca-central-1.amazonaws.com\/xxxxx-uploads\/users\/avatar\/fae764d0abea565f8e8524805a3285579568f7f2.jpg"
How can I remove the extra slashed from this string using javascript?
Because it seems that the content you're given is a valid JS or JSON string, you can use JSON.parse() or eval() to convert it from the serialization to actual JS string data without the quotes and escape sequences.
We'll use JSON.parse for safety since you're getting it from an external source.
var s = JSON.parse(url_data);
console.log(s);
I would like to send data from the server to the client, where javascript code can access the data. This is basically a string message, what I would like to embed in my custom attribute like this:
<div my-message="here is my custom data">
After short testing I recognized the message itself can contain special char like " so the html will be incorrect after embedding.
What is the correct way to (encode?) the string data? (server side is ASP MVC)
Is there any javascript support to decode the string? Obviously say base64 can do it, but it sounds a bit weird, and also I would not like reinvent the wheel here.
For server side:
Razor
<div data-my-message="#("your string with \" goes here")">
Or if you hold the string in the Model
<div data-my-message="#Model.Message">
ASPX
<div data-my-message="<%: "your string with \" goes here" %>">
Razor's #() or ASPX's <%: %> will encode it correctly.
BTW If you want to embed your string directly in the view you can escape the " with \"
For client side:
You can read it easily with jQuery
$(selector).data("my-message")
or plain javascript
document.querySelector(selector).dataset.myMessage
Also you should prefix your custom attributes with data- as #Erik Philips says in the comments
You can use the functions encodeURI and encodeURIComponent for encoding. And for decoding the functions decodeURI and decodeURIComponents.
You can look them up for example here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
If you want to send arbitary data (i.e. arrays, objects, etc.) then I use the following:
use a data-foo attribute on the tag
json-encode the data
Use single quotes around the attribute value (JSON uses double quotes for strings)
Replace any single-quotes in the json-encoded string with the corresponding thml entity (’)
Something like (I did it in PHP so the .net syntact might be slightly wrong
<% Dim Serializer As New System.Web.Script.Serialization.JavaScriptSerializer %>
<div data-foo='<%=Serializer.Serialize(MyData).Replace("'", "’") %>'>Some content</div>
Where the data to use is in the variable MyData
Has the advantage that when you get out the data you get an object back automatically (at least, with jQuery but I would imagine with plain js too - if not then it's easy to recreate the object)
Update
Following the comment about double quotes, if your data is just a string then you should replace double quotes buy their html entity too. Or ensure you json-deode. It's not automatically recognised as json data and decoded if it's just a string. PHP (where I have used this more) encopdes double quotes in the string as \". I have a memnory that in vb.net you need to change Serializer.Serialize(MyData).Replace("'", "’") to Serializer.Serialize(MyData).Replace("\", "\\").Replace("'", "’") becuase of how it handles quotes. If the data is an object then it is automatically json-decoded when you get it out and alls is OK. if the data is just a string then don't need to json-encode maybe - just change at least one of the type of quotes (either single or double quotes) to html entities and use that quote type around the attribute.
As long as you get the quoting right it handles html in the data fine: see http://jsfiddle.net/ctueo7sr/ for a simple string example and http://jsfiddle.net/aLaLnhp2/1/ for an object example
I wanna pass %20 in Query string. But in code behind it will considered as space in code behind.
How can i do that?
I am passing querystring using asp.net and also from javascript.
Please help me out for the same. Thanks in advance.
When you pass value from Asp.net code behind use Server.UrlEncode(%20)
When you pass value from JavaScript use encodeURIComponent('%20') (which will yield %2520)
Pass %2520 to escape your %, that's how.
I'm trying to dynamically add contents of a div using JS. Back end is Ruby on Rails. I am having a problem. Here's what is included in the view file:
var product_sidebar_inner = "<%= CGI.escapeHTML(render(...some partial...)).gsub(/\r/," ").gsub(/\n/," ") %>";
document.getElementById("left_sidebar_wrapper").innerHTML = unescape(product_sidebar_inner);
The above inserts html as text to div#left_sidebar_wrapper. Spent some time on this but still can't make this work. Any idea what am I am doing wrong?
Based on your comment to macarthy, I think you want CGI.escape (or CGI.unescape), that's what you use for URL encoding. You can also use URI.escape (or URI.unescape) but you'll get tired of having to pass the unsafe regex all the time to get it to do what you want.
Also, on the JavaScript side, you should be using encodeURI or encodeURIComponent as escape is deprecated because it has problems with non-ASCII characters.
THink you need to use raw
unescape(raw(product_sidebar_inner));
i have an Html String in which i have some elements having single quotes.When i put this inside a $('varHtml'); Since the varHtml already contains some single quotes it qives an error, Can Somebody help me how to Escape the single quotes in the varHtml
Thanks in Advance
Thomson
If you have a HTML string in a variable, then you don't need to put it in quotes:
var varHtml = "<div id='foo'></div>";
$(varHtml);
javascript lacks something like an htmlencode to run client side. So you will have to use one of the script libraries. You can try this jQuery solution:
http://www.edentity.ca/WhoWeAre/Blog/Easy-Client-Side-html-EncodeDecode-using-jQuery.aspx
Or you could simply use a javascript string replace function like the one explained here: http://www.w3schools.com/jsref/jsref_replace.asp. Replace ' with ' or the HTML code you prefer. Reference: http://www.degraeve.com/reference/specialcharacters.php