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

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%");

Related

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

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.

Setting up a javascript url

I simply want to set up an ajaxurl in javascript to pass to my controller.
When trying to setup the url, it evaluates to 0 during the below attempts:
Note that attrs.attachmentType & attrs.attachmentId have values associated with them.
var hoser = attrs.attachmentType & attrs.attachmentId;
ajaxUrl = root + 'FileUpload/upload?' & 'Type=' & attrs.attachmentType & 'ID=' & attrs.attachmentId;
If I just include the following, a proper value is seen inside the hoser variable.
var hoser = attrs.attachmentType;
What am I doing wrong where the url will not come out correctly?
You are using & symbols, not adding them to the string. By using these symbols, javascript is interpreting the right hand side of your statement to be a comparison and outputting the answer it thinks you want - in this case, a boolean representation of false: 0
Change your & symbols to strings. Like so:
ajaxUrl = root + 'FileUpload/upload?' + '&' + 'Type=' + '&' + attrs.attachmentType + '&' + 'ID=' + '&' + attrs.attachmentId;

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.

how to get full path of URL including multiple parameters in jsp

Suppose
URL: http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
<%
String str=request.getRequestURL()+"?"+request.getQueryString();
System.out.println(str);
%>
with this i get the output
http:/localhost:9090/project1/url.jsp?id1=one
but with this i am able to retrieve only 1st parameter(i.e id1=one) not other parameters
but if i use javascript i am able to retrieve all parameters
function a()
{
$('.result').html('current url is : '+window.location.href );
}
html:
<div class="result"></div>
i want to retrieve current URL value to be used in my next page but i don't want to use sessions
using any of above two method how do i retrieve all parameters in jsp?
thanks in advance
Given URL = http:/localhost:9090/project1/url.jsp?id1=one&id2=two&id3=three
request.getQueryString();
Should indeed return id1=one&id2=two&id3=three
See HttpServletRequest.getQueryString JavaDoc
I once face the same issue, It's probably due to the some testing procedure failure.
If it happens, test in a clear environment : new browser window, etc.
Bhushan answer is not equivalent to getQueryString, as it decode parameters values !
I think this is what you are looking for..
String str=request.getRequestURL()+"?";
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements())
{
String paramName = paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++)
{
String paramValue = paramValues[i];
str=str + paramName + "=" + paramValue;
}
str=str+"&";
}
System.out.println(str.substring(0,str.length()-1)); //remove the last character from String

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