I am using asp.net MVC 3.0. I want Passing parameter with URL. It works. But if my parameter value is like shahin & karina. Then it count as a two value beacuse of &. I want to inculed & as a vlue. How can I do that. Please, Anyone has solved this kind of problem.
For example:
My controller function is:
public ActionResult Index(string name)
{}
html code
<a href="/stat?name=shahin & karina">
Form the controller I got only name value is: shahin
But I need Name value is: shahin & karina
Thanks advance..
I believe all you would need to do is URL encode the ampersand (and possibly the space character).
Try something like this -
<a href="/stat?name=shahin%20%26%20karina">
%20 is an encoded space character.
%26 - is the encoded ampersand character.
I have absolutely zero knowledge or experience with asp.net but I'm fairly sure that there are native URL encoding functions...
You need to encode the URL. There is surely a library for it in .NET.
Similar tools:
http://meyerweb.com/eric/tools/dencoder/
Cheers
HH
You have to encode '&' as an HTML entity.
<a href="/stat?name=shahin%20%26%20karina" />
Try rewriting the html code as:
<a href="/stat?shahin%20%26%20karina" />
%20 is a url-encoded space and %26 is the url-encoded ampersand
You can use this tool to try encoding different strings (in this example, you would encode "shahin & karina")
Related
My url is as follows
document.writeln("<form name='statistics' action='submit.php?p='+precision+'&r='+recall+'&a='+accuracy; onsubmit='return validateForm()' method='get'>")
document.writeln("<button style = 'font-size: 32px; float : right'class = 'button' > See results </button>")
document.writeln("</form>")
Where the url string is
'submit.php?p='+precision+'&r='+recall+'&a='+accuracy;
I have also tried
'submit.php?p='+precision+'%26r='+recall+'%26a='+accuracy;
However neither give me ampersands in the browser.
The url I get in my browser for both cases is as follows -
http://localhost/WT2ASST1/submit.php?p=1r=0.4a=0.4
I have not added any other relevant code with respect to the form submission and the url.
What do I need to do to get ampersands in my url?
you're using the wrong string concatenation.
this should work:
document.writeln("<form name='statistics' action='submit.php?p="+precision+"&r="+recall+"&a="+accuracy+"' onsubmit='return validateForm()' method='get'>");
document.writeln("<button style = 'font-size: 32px; float : right'class = 'button' > See results </button>");
document.writeln("</form>");
note: if you want to concatenate strings you have to use the correct string delimiters e.g. "test"+var+"test"
not "test'+var+'test"
This should give you ampersands (it did for me)
document.writeln("<form name='statistics' action='submit.php?p='+precision+'&r='+recall+'&a='+accuracy; onsubmit='return validateForm()' method='get'>")
But, the whole thing is in double quotes, so + will be a literal string instead of being an operator. In the second case, you have an encoded URL. Document.write won't magically decode those for you. You could use the decodeURI function, but then it'd be the same if you'd just use the literal "&" to begin with.
Use your first method, but use double quotes to indicate where each string ends and where you want to concatenate a variable. Like so
document.writeln("'submit.php?p='"+precision+"'&r='"+recall+"'&a='"+accuracy);
A quick note, you would only encode ampersands if you're not using them for their intended purpose of separating GET variables; which is how you're using them. Encoding those would likely just confuse the server.
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 am trying to pass the Euro ( € ) sign as url parameter in my spring jsp. What is the right way to do so ? I tried the following with no avail. Problem is the character is getting encoded properly but not getting decoded from my destination jsp.
I am using
<%#page contentType="text/html;charset=UTF-8" %>
Here is the calling jsp:
<script>
...
// params contains the euro sign
document.location='dest.jsp?p='+escape(params);
In the dest.jsp
<input type="hidden" id="par" value="${param.p}">
and in a script in the same page
console.log($('#par').val())
when I use escape(params) I get the url as %u20AC . But no (empty) values in the dest.jsp
when I use encodeURI(params) or encodeURIComponent I get url as € . But the value in dest.jsp as ⬠- something which I can't use to render as euro sign
I'm going to assume you are using Tomcat because that's what I tested with and we get the same result.
What you will want to do is open up your Tomcat servlet.xml file and find the HTTP connector and add the useBodyEncodingForURI attribute with the value true.
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1"
redirectPort="8443" useBodyEncodingForURI="true">
</Connector>
Then, you will want to register a CharacterEncodingFilter to set the HttpServletRequest character encoding.
You can read more about this behavior in my answer here:
Character encoding in query string, hebrew
You need indeed to encode the € sign which should give %E2%82%AC using UTF-8. You need to be careful with the encoding you use on both ends.
Something like URLEncoder.encode(url, "UTF-8") on the client would do.
If you are using Spring, org.springframework.web.util.UriUtils has also nice utilities you can use.
If the decoding issue is on the server, you need first to make sure that your web container decodes the URI with the proper encoding.
Tomcat decodes URI with ISO-8859-1 by default so you need to update your connector configuration
<Connector port="8080" ...
URIEncoding="UTF-8"/>
See the following answers
Spring MVC: How to store € character?
Getting question mark instead accented letter using spring MVC 3
I think that org.springframework.web.filter.CharacterEncodingFilter should help here.
Try it with and without your encodeURI(params)
I am trying to analyse some JavaScript, and one line is
var x = unescape("%u4141%u4141 ......");
with lots of characters in form %uxxxx.
I want to rewrite the JavaScript in c# but can't figure out the proper function to decode a string of characters like this. I've tried
HttpUtility.HTMLDecode("%u4141%u4141");
but this did not change these characters at all.
How can I accomplish this in c#?
You can use UrlDecode:
string decoded = HttpUtility.UrlDecode("%u4141%u4141");
decoded would then contain "䅁䅁".
As other have pointed out, changing the % to \ would work, but UrlDecode is the preferred method, since that ensures that other escaped symbols are translated correctly as well.
You need HttpUtility.UrlDecode. You shouldn't really be using escape/unescape in most cases nowadays, you should be using things like encodeURI/decodeURI/encodeURIComponent.
When are you supposed to use escape instead of encodeURI / encodeURIComponent?
This question covers the issue of why escape/unescape are a bad idea.
You can call bellow method to achieve the same effect as Javascript escape/unescape method
Microsoft.JScript.GlobalObject.unescape();
Microsoft.JScript.GlobalObject.escape();
Change the % signs to backslashes and you have a C# string literal. C# treats \uxxxx as an escape sequence, with xxxx being 4 digits.
In basic string usage you can initiate string variable in Unicode:
var someLine="\u4141";
If it is possible - replace all "%u" with "\u".
edit the web.config the following parameter:
< globalization requestEncoding="iso-8859-15" responseEncoding="utf-8" >responseHeaderEncoding="utf-8" in < system.web >
I have a MVC view in which I have to pass a string variable to JavaScript, but that string variable has single quotes in it ('). I am trying to do something like this
<a onclick="JavaScript:AddressHandler.ProcessAddress('<%= homeAddress %>');"
class="button-link">change</a>
homeAddress has single quotes which I have to workaround somehow so that I can pass the complete value of it to the JavaScript.
You can use Ajax helper: Ajax.JavaScriptStringEncode(string strToEncode)
To escape a string to be a Javascript string literal, you replace backslash with double backslashes, and the string delimiter with a backslash and the delimiter:
<a onclick="AddressHandler.ProcessAddress('<%= homeAddress.Replace(#"\", #"\\").Replace("'", #"\'") %>');" class="button-link">change</a>
Note: The javascript: protocol is used when you put script in an URL, not as an event handler.
Edit:
If the script also contains characters that need HTML encoding, that should be done after escaping the Javascript string:
<a onclick="<%= Html.Encode("AddressHandler.ProcessAddress('" + homeAddress.Replace(#"\", #"\\").Replace("'", #"\'") +"');") %>" class="button-link">change</a>
So, if you don't know what the string contains, to be safe you need to first escape the string literal, then HTML encode the code so that it can be put in the attribute of the HTML tag.
You can write a method that escapes all single quotes (and other characters if needed) with a backslash so it is not misunderstood by javascript.
You'll want to encode homeAddress as a URL. MVC has a built in helper to do this: UrlHelper.Encode(string url) - it should replace a single quote with %27
I don't have time to test it, but look at HtmlHelper.Encode(string s). It might handle the escaping for you.