Encoding and decoding between Javascript and c# - c#

I want to be able to send data to Javascript in a div like this:
<div class="dontDisplay><%= myData %></div>
However, the challenge is that the HTML will get messed up. There seems to be a plethora of encoding and decoding schemes out there, but I can't find a javascript/C# pair that are guaranteed to be compatible for all possible inputs (including Unicode.)
Does anyone know of a pair that are known to be perfectly compatible?
Thanks

You most probably want to use json. You can embed a string in your page that creates a local variable on your page using json inside a script-tag:
<script> var myJsonVariabe = { propertyNane: "value" }; </script>
You can serialize a .net object to json using the DataContractJsonSerializer.

You appear to be just putting some text into HTML text content, for which the correct approach is plain old HTML-encoding:
<div class="dontDisplay"><%= Server.HTMLEncode(myData) %></div>
or in ASP.NET 4.0:
<div class="dontDisplay"><%: myData %></div>
If JavaScript needs to extract this, you can use DOM methods:
<div id="foo"><%= Server.HTMLEncode(myData) %></div>
<script type="text/javascript">
var myData= document.getElementById('foo').firstChild.data;
</script>
although this assumes that there's exactly one text node in there, and will break if myData is an empty string. You can work around this by having a getTextContent method that checks all the childNodes for being text nodes and adds their data together, or use textContent with fallback to innerText for IE, or use a library to do it (eg. text() in jQuery).
alternatively you can put the data in an attribute:
<div id="foo" title="<%= Server.HTMLEncode(myData) %>">...</div>
<script type="text/javascript">
var myData= document.getElementById('foo').title;
</script>
if there is a suitable attribute available (title might not be appropriate), or a comment, or directly into a JavaScript variable using JSON as suggested by Rune.

Related

Binding ckeditor content to model in asp.net 5 without using js

I try to retrieve data from a ckeditor but failed. My code is as follow
#model Test.ViewModel.MyViewModel
<textarea name="my-textarea" asp-for="content" class="form-control form-gap" placeholder="Main Content"></textarea>
<script type="text/javascript"> CKEDITOR.replace('my-textarea'); </script>
I bind the textarea to an element called content in MyViewModel. If I don't use ckeditor, I am able to get the content in textarea in my action. However, if I use ckeditor, I am not able to do so. I saw some articles talking about using javascript, but I would like to use C# itself. Can anyone help to see what is wrong and what I should do. Thank you.
So, this is untested and I've always used the ckeditor with JavaScript, but searching on nuget I found this package https://www.nuget.org/packages/CKeditor.Mvc that I think you can use. In
http://forums.asp.net/t/2012709.aspx?How+to+Implement+a+CKeditor+in+MVC, someone elaborates on how it can be used.
//Notice the attribute (AllowHtml)
public class BlogEntry {
[AllowHtml]
public string BlogText {get;set;}
}
Add this to your view
#model MyProject.ViewModels.BlogEntry
And, of course, have your input
<input type="text" id="BlogText" name="BlogText" />

Moving text in .Net without refreshing page

I am still new to the coding field and am having a bit of trouble with a part, hoping someone can help me. I am working on a MVC page where i am trying to move text, the user inputs, around the page to a few pre-set spots and without having to refresh the page. Do i need a type of script for this? And if i do what would be best? Thanks for the help.
You can do it this way.
Enter Text here... <input id="testText" type="text" onKeyUp="javascript:showText($(this), event);"/>
<br/>
<br/>
<br/>
See it here... <span id="testTextSpan"></span>
Then, add this script...
<script type="text/javascript">
var showText = function (el, e) {
$('#testTextSpan').html(el.val());
};
<script>
See it here in this JSFiddle...
http://jsfiddle.net/ZEcNp/
Be sure to include JQuery libraries in your project, or reference the CDN.
If you'd like me to include an example with raw javascript, with no JQuery, I can also provide that for you.
I would recommend jQuery to do all that client-side.
You would just need an ID for each element you would use as the predefined spots, using either .appendTo, .insertAfter, .html, or something else depending on your exact needs.

format string containing html

I have a simple string variable that contains a portion of HTML inside. For example:
string contents = "<div><p>Hi how are you. Click here if you want to know more";
I want to include this HTML in page:
<div class="description">
#contents
</div>
However, it messes up the rest of the page because of unclosed tags.
Is there a function (or a helper) that reads and formats the HTML inside for example, to complete the HTML without errors:
#Html.DisplayProperHTML(contents)
This will render as:
<div><p>Hi how are you. Click here if you want to know more</p></div>
There is no such functionality built-in.
You can use the HTML Agility Pack to parse and fix broken HTML.

"Expected expression" with <%=foo%> inside JavaScript in .aspx file

I've got code like this in an .aspx file:
<script type="text/javascript" language="javascript">
function init()
{
<%= x %>
}
It works fine (x is a string that will be bound to some JavaScript at runtime), but when compiling I get an "Expected expression" warning on the <%=
I know it's not the nicest code in the world, but there are various historical bits of code that like to inject little bits of JavaScript into the page. All perfectly innocent :)
The warning is happening because the code block is inside a JavaScript <script> block; the compiler is trying to be smart about recognizing the difference between HTML/controls and JavaScript.
Although it's a bit ugly, you should be able to eliminate the warning by using eval('<%= x %>')
You might also have a look at an article I wrote on using ASP.NET to create dynamic JavaScript: http://www.12titans.net/p/dynamic-javascript.aspx
If you wanted to be perfectly legal, use a literal:
<asp:Literal ID="litX" runat="server"></asp:Literal>
and set its Text to the whole <script type="text/javascript" language="javascript">...</script> block on the server side.
Visual Studio is validating the HTML markup on the page. Strictly speaking, the '<' is not valid XHTML. This warning may be caused by a limitation of the validation as Visual Studio is interpreting the '<' character inside javascript as meaning 'less than'!
Obviously these inline expressions are not valid client code. One can change the HTML validation options in Tools|Options|Text Editor|HTML. Mind you, it may be better to simply ignore these warnings rather validate against HTML 4.01 or turn off the validation completely.
If all you're doing is adding javascript to your page, you could use RegisterClientScriptBlock to build the script server-side and then let it output it to the page.
This way you don't have to have any server-side scripting within your page and all the overhead that goes with that.
I've done this before and not had problems. However, I use jQuery's $(document).ready() instead of init(). I don't think that should be an issue, though.
What datatype is x? If it is a string, try wrapping it in single quotes, and if it's a number use the parse function for that datatype.
<script type="text/javascript" language="javascript">
var s;
var n;
function init()
{
s = '<%= x %>';
n = parseInt('<%= x %>');
eval('<%= x %>'); /* Raw Javascript */
}
</script>
Another issue would be the access level of the property. ASP.NET web forms can't access private fields directly from the code-behind. Access has to be protected or public.
Eval Javascript Function
I found the problem that I was having with this.
It seems I had incorrectly commented out HTML above the script.
<%-- <div id="directionpanel" ></div>--%>
<script type="text/javascript">
var LIST = <%= getJson()%>;
</script>
I was getting the expected expression warning on getJson()
Correctly commenting the HTML will fix the warning.
-->

Use .ascx to render content from ajax call

Assume I have on a page an article with the possibility to comment it. I have a submit form that submits via ajax and the OnComplete javascript method intercepts the result of the form submit.
Each comment is smth like:
<div class="text">
<p class="details">
User Always_Dreaming at 01/01/2009 - 11:13:52 </p>
<p>Here goes my text :D</p>
</div>
I made an .ascx file from it, and I do tml.RenderPartial foreach comment. Now the question is how can I use this .ascx control to output the inserted content to the OnComplete method from client side.
PS. I want to use this approach and not to serialize the Comment object and to return the serialized data, take it wioth my js code and generate on the fly the html with data from the deserialized Comment object.
What you need to do is use the PartialViewResult from the action that's invoked by your javascript call. The client side code can append it to the html using something like the jQuery append or html method calls.
for those who are interested, I found a sample :)
here

Categories