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's_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?
Related
I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all®ion=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')
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);
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
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();
}
I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");
how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me
thanks
In that function, you could use the server side code tag.
var string = "<% = myString%>"
You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).
var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover", attributeValue);
Try this:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");
Two ways:
Method 1 (Jon Martin's way): Have a javascript variable populated by server information
Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
Populate _mystring on the code behind: public String _mystring = "your value";
Method 2: Just dump the variable out from the server side
Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);