Problems with encoded special characters using $windows.location and ASP.NET MVC - javascript

I have a javascript code where I do a window.location to an .net mvc action. id is a number e.x. 1234, while name is a name with special character. E.x. "Røed"
$window.location = "/mycontroller/myaction/?id=" + query.id + "&name=" + query.name;
In fiddler I can see that the request url becomes:
mydomain.com/controller/action/?id=1234&name=R%C3%B8ed
When I in my ASP.NET MVC controller tries to get the query string values from Request.QueryString, I get something which looks like a double encoded string:
public ActionResult MyAction(LandingPage currentPage, string state)
{
string queryString = Request.QueryString.ToString();
var cultureName = CultureInfo.CurrentCulture.Name;
querystring becomes: "id=1234&name=R%u00f8ed"
As you can see, the encoding from the request url doesn't look the same as the one in asp.net. why?
I need to use the decoded name further in my application (Røed). How can I accomplish this?

Try this on the javascript side (to ensure you encode each part correctly):
$window.location = "/mycontroller/action/?id=" + encodeURIComponent(query.id) + "&name=" + encodeURIComponent(query.name);
and this on the MVC side:
public ActionResult Action(string id, string name)
{
}
or, using your example now that you've provided it:
public ActionResult MyAction(LandingPage currentPage, string state, string id = null, string name = null)
{
if (id != null && name != null)
{
}
}
and then name should be interpreted correctly. Because you're using the QueryString directly, it's the encoded query string.
If you really need to, you can parse the query string using HttpUtility.ParseQueryString(...) which will give you a NameValueCollection, but this isn't the correct way to do things.

Related

What role in a string has # when passing string parameters via JS (Fragment identifier)

I have recently experienced a problem when passing string parameters via JS to controller action if string contains #, it would ignore the next parameter.
JS
window.location.href = $ele.data("url") + "?title=" + $ele.data("title") + "&employeeId=" + $ele.data("employeeid") + "&suggestionId=" + $ele.data("suggestionid") + "&statusId=" + $ele.val() + "&communicationId=" + $ele.data("communicationid");
C#
public ActionResult StatusUpdate(string title, Guid employeeId, Guid suggestionId,
int statusId, Guid? communicationId)
{
var suggestion = new SuggestionView
{
SuggestionStatusId = statusId,
SuggestionId = suggestionId
};
return new HttpStatusCodeResult(200);
}
So if $ele.data("title") contains #, in the controller action the next parameter or more specifically employeeId in this particular case would come as NULL, and it wouldn't pass the data properly since employeeId is not a nullable Guid.
Why is a controller action ignoring parameters after the #?

json converting characters to random charaters

Hi i have email address in my database e.g "abc#yahoo.co.in" and when I retrieve it i am getting the same on my controller as well before returning that object to client but when i alert that value on my java script page, "#" is converting to some random characters and not giving proper display. How can i solve this.?
server code :
enter code here
public AppUser findById(#FormParam("employeeId") String eId ){
int id=Integer.parseInt(eId);
AppUser appUser=null;
appUser= evaluatorService.findById(id);
return appUser;
}
while debugging appUser it is giving me proper data.
my client side code :
$.ajax({
type : 'GET',
url : 'rest/evaluator/fetchEvaluatorById',
data : {
'employeeId' : employeeId
},
success : function(data) {
$('#evaluatorDetailEdit').dialog({
width: 400,
height: 400,
});
alert(data.email);
$('#employeeId').val(data.employeeId);
$('#name').val(data.name);
$('#lastName').val(data.lastName);
$('#email').val(data.email);
}
});
There is some hacky jquery-workaround - maybe there are better solutions, but this should work:
var original = "#";
alert("Original: " + original);
// Hacky jquery-workaround:
// 1. pasting encoded text as html in a "virtual" textarea and
// 2. get the decoded text:
var decoded = $('<textarea/>').html(original).text();
alert("Decoded: " + decoded);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
According to your comment, every # are change to #.
In fact, # is the HTML entity to represent the character #.
You should convert (HTML entity decode) the character on your server.
For example, in PHP, just call this function on your email strings: http://php.net/manual/en/function.html-entity-decode.php

Encoding URL Query String Value from JavaScript to ASP.NET MVC

I have an app that uses ASP.NET MVC and JavaScript. I am generating a URL in my JavaScript like this:
// Imagine 'filter' is "AT&T".
var v = filter.replace(/'/g, "''");
v = v.replace(/&/g, "%26%");
var t = "(clause eq '" + v + "')";
// At this point, t is "(clause eq 'AT%26%T')"
window.location = '#Url.Content("~/find?")' + 'q=' + t;
In my ASP.NET MVC controller action, I have the following:
public ActionResult Find(int? id, string q)
{
// do stuff
}
If I set a breakpoint in the Find action, I notice that q is the following:
(clause eq 'AT&%T')
I'm not sure why. I need it to be (clause eq 'AT%26%T'). What am I doing wrong? I understand its some encoding issue.
The reason for this is that your encoded ampersand %26 is UrlDecoded serverside back to &. If you want to keep the url encoded version you need to escape the percent sign % too with its encoded equivalent %25:
v = v.replace(/&/g, "%2526%");

Java Script to MVC: Controller Variable Passing via Actionlink

Using: vs'12 Razor asp.net MVC4 Internet App Template EF Code First
My Actionlink that i am trying to manipulate
#Html.ActionLink("Download", "ShowOpenAcreageSummaryReport", new { controller = "DataToExcel" }, new { id = "AddData" })
The script to attempt this
$('#AddData').click(function (e) {
var optVal = $("#OptionsDrop").val();
var Xpro = $("#Prospects").val()
var Xcnty = $("#Countys").val()
var Xtwn = $("#TownShips").val()
var Xrng = $("#Ranges").val()
var Xsct = $("#Sections").val()
var href = "/DataToExcel/ShowLPRStandardLeaseReport/" + Xpro + Xcnty + Xtwn + Xrng + Xsct;
this.href = ""; //clears out old href for reuse
this.href = href; //changes href value to currently slected dropdown value
}
The actionResult to accept these passed values
public ActionResult ShowLPRStandardLeaseReport(string pro, string cnty, string twn, string rng, string sec)
Now i know this works with 1 variable as i have this code running on another page, however it won't work with multiple.
I have also tried adding + "/" + between the Variables, which had no effect on the outcome.
How can i change my code to be able to pass all variables??
Have you tried with GET parameters such as some-url/?param1=test&param2=test2 ? Also note that this points to the #AddData element in the click handler. If you want to change the current location, use window.location.href = 'someurl';
The ? is necessary to indicate the start of the query string parameters.
Also note that you should be encoding the values with encodeURIComponent to make sure that you are producing a valid URL.

url encoding with javascript window open

ASP.NET 4.0, webform site
There is a link in my site is to call another page and pass url parameters, it looks like below.
http://www.foo.com/foo.aspx?anotherURI?param1=aaa&26param2=bbb
However, I need to do url encode for "anotherURI?param1=aaa&26param2=bbb", so it turns into:
http://www.foo.com/foo.aspx?anotherURI?param1%3Daaa%26param2%3Dbbb
Now if I want to enclose this with javascript, it won't work. How do I encode the url again?
javascript:void(window.open('http://www.foo.com/foo.aspx?anotherURI?param1%3Daaa%26param2%3Dbbb', 'popup'))
Correct the URI:
WRONG: http://www.foo.com/foo.aspx?anotherURI?param1%3Daaa%26param2%3Dbbb
RIGHT: http://www.foo.com/foo.aspx?anotherURI=param1%3Daaa%26param2%3Dbbb
Example for multiple URIs: http://www.foo.com/foo.aspc?uri1=[encodedURI]&uri2=[encodedURI2]
To get a value from a queryString variable on asp.net:
Dim sUrl1 as String = request("VarName")
Dim sUrl2 as String = request("VarName")
Dim sUrl3 as String = request("VarName")
If you want to get the decoded URL from that variable:
Dim sDecodedUrl1 as String = Server.UrlDecode(sUrl1)
Dim sDecodedUrl2 as String = Server.UrlDecode(sUrl2)
Dim sDecodedUrl3 as String = Server.UrlDecode(sUrl3)
if you want to encode/decode it (the way php does it) use
function url_encode(str) {
str = (str + '').toString();
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28'). replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
function url_decode(str) {
return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}

Categories