how to solve C# Json Serialization parsing in javascript with quoutes? - javascript

I am serializing a C# Class AnnouncementClass
public class AnnouncementClass
{
public string application;
public List< AnnoucementsMessages > annoucements = new List<AnnoucementsMessages>();
}
public class AnnoucementsMessages
{
public string message;
public string startdate;
public string priority;
}
using the serializing method
string jsonboj = new JavaScriptSerializer().Serialize(announcementClass);
after that I write the json in the javascript by using the <%# > Tag and perform a page.databind() in the page and later in javascript y I use Json.Parse(jsonObj) to generate the json file
but that's giving me a problem
if in the message part i insert a double quoute it breakes the json.parse, even if i try to scape it.
Is there a proper way to translate the json to the javascript side?
do i need to replace something before the c# serialization ?
Thank you

Solution found, thank you
when parsing , Javascript will reduce all the scapes so, using \" = " and \\="
so i had to replace the \" with ;quot

Related

Passing params through URL - Single quotes become '

I'm working with a ASP.NET project. We are passing params through the url and every time a single quote is passed the url changes all single quotes to %27 and the actual value read in through the javascript changes all single quotes to '
Can someone tell me how I can maintain the single quotes as our parameters need to match the exact values. This is my code.
public class Model
{
public string example {get; set;}
}
public ActionResult Index(string example)
{
var model = new Model();
model.example = example;
return View(model);
}
Index.cshtml at the bottom ---------------------
<script type="text/javascript">
var example = "#Model.example";
Main();
</script>
Javascript -----------------
console.log(example);
Examples: www.example.com?example=Turtle's_Are_Cool
Changes the url instantly to => www.example.com?example=Turtle\%27s_Are_Cool and the JavaScript outputs Turtle&#39s_Are_Cool
If you want to do it on the server side you can use
Server.URLEncode("Turtle's_Are_Cool"))
If you want to manage the same on client-side you can replace ' with '
example = example.replace(/'/g, "\'");
But if you have got a single quote coming from server-side and you want to convert it at client-side then the easiest way is to use HTML element as shown in the below question
Unescape apostrophe (') in JavaScript?

build a string in javascript using single quotes

Hi I want to build a string in javascript. I am sure I am missing something here. I have been trying from long time
'#StringUtils.FormatStringParameter(ValidationMessages.ContractDeleteBudgetValidation,'+ data + ')'
Data is a variable that i want to pass. FormatStringParameter is a utility class i have in C#. I want to use that utility class in javascript.
public static string FormatStringParameter(string strng, params object[] listParameters)
{
return String.Format(strng, listParameters);
}
public const string ContractDeleteBudgetValidation = "Contract has been budgeted. Are you sure you want to {0} ?";
In c#, when you use single quotes to wrap around a char, it will try to create an object of System.Char. But when you do that you should always pass a single character. In your example, you are passing more than one char('+ data + '). So you are going
to get an error "Too many characters in character literal"
If data is a c# variable, you should be calling it like this
var yourJsVariable = '#StringUtils.FormatStringParameter(
ValidationMessages.ContractDeleteBudgetValidation, data )';
alert(yourJsVariable);

Convert Html to plain text

I used tinymce editor for rich text editor. My problem is when i save the text, its saves in html format like
<p> Hello world<p/>
I need a plain text i.e. "Hello World" in above example.
I search on google and I find something like html encode. I don't know what that is. I am new to this concept. I am using asp.net MVC 5 and I have used tinymce as:
Model is
namespace ProjectNSAS.Models{
public class AboutModels
{
[Key]
public int Id { get; set; }
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Content { get; set; }
}
It's probably not the best of help,, but a .txt file is also a form of plain text. If you just want to see the code and not run it, try doing something with .txt.
HTML has some characters which mean special things to HTML. Specifically, opening and closing tags ("<" and ">"), when put together, mean that the content between them specifies an element. If you have these characters when they aren't meant for HTML tags, HTML parsers have trouble. When an HTML file wants to represent literal greater-than or less-than characters, it "encodes" them by replacing them with ">" and "<", respectively. Browsers and other HTML-consuming products know that those two strings represent "escaped" HTML characters.
.NET has a small library for escaping/unescaping HTML strings - it's the HttpUtility class. specifically, check out HttpUtility.HtmlEncode and HttpUtility.HtmlDecode
Under the hood the editor provides a getcontent method, the integration doesn't provide an access point that I can easily find. However the implementation is rather simple.
TinyMCE has the following code to convert it's html to text:
In: jquery.tinymce.js:
... t.getContent().replace(/<(?:"[^"]*"|'[^']*'|[^'">])*>/g, "") ...
Which basically is just a javascript regex replacement, do the same in your C# code, and then decode the html.
Here is a sample controller:
public class TinyController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(TinyMCEModelJQuery model)
{
var foo = model.Content;
Regex regex = new Regex("<(?:\"[^\"]*\"|'[^']*'|[^'\">])*>");
var htmlPlainText = regex.Replace(foo, string.Empty);
var plainText = HttpUtility.HtmlDecode(htmlPlainText);
// do what you need with plainText
return View();
}

how serialize in code behind and de serialize in JavaScript then serialize in JavaScript and de serialize in code behind

I use web service and know how to send and receive string between code behind and JavaScript.
but now I have a 2D array and xml that I need to send and receive between code behind and JavaScript.
so:
1 - Is serialize and send a string is the best way?
2 - how can I do it?
to serialize in code behind:
Dim serializer = New JavaScriptSerializer()
Dim createArrayScript As String = serializer.Serialize("{for example my array}")
to de serialize in JavaScript
download and use json-serialization.js from below linkg:
then:
var obj = JSON.parse("{received string from code behind}");
to serialize in javascript
download and use json-serialization.js from below linkg:
then:
var str = JSON.stringify("{for example my array}");
to de serialize in code behind:
Dim my_array As Object = New JavaScriptSerializer().Deserialize(Of Object)("{received string from javaScript}")
I think this method convert 2d array to simple one, this site json.codeplex.com/ says his solution is better, but i didn't check.
for more information:
http://www.sitepoint.com/javascript-json-serialization/
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
[Kian Fatt, Ting] I think you can use DWR for java script, DWR allows you to store your data in a database table to later retrieve it back would that solve your problem?

javascript won't pass json string ~ System ArgumentException

I have a json string which I'm trying to pass into a silverlight command from my javascript. This is the line of code I'm trying to run:
silverlightPlugin.Content.essentialsViewer.RunCommand("findShapeInArea", "{'area':0,'shape':77}");
This works in Visual Studio 2010 but when I upload it to IIS7 and test I get this error when it runs:
"System.ArgumentException: Can not convert Integer to String. at System.Windows.Browser.ManagedObjectInfo.Invoke(ManagedObject obj, InvokeType invokeType, String memberName, ScriptParam[] args)
at System.Windows.Hosting.ManagedHost.InvokeScriptableMember(IntPtr pHandle, Int32 nMemberID, Int32 nInvokeType, Int32 nArgCount, ScriptParam[] pArgs, ScriptParam& pResult, ExceptionInfo& pExceptInfo)"
I'm not sure why it thinks that it's trying to convert and Integer to a String. Does anyone know what's going on here?
Ok I figured out the issue. When passing a json string like I've done above if the parameter is asking for a string then everything inside the json object must be of type string even though it's already a string as a whole. So the code below worked:
silverlightPlugin.Content.essentialsViewer.RunCommand("findShapeInArea", "{'area':'0','shape':'77'}");

Categories