Java Script to MVC: Controller Variable Passing via Actionlink - javascript

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.

Related

adding parameter values inside of parenthesis while using scala.html

i would like to add dynamic parameter values (not sure if i can call it like this)
to the url in my scala html.
Using javascript, I get userId first and then would like to pass it to #routes.adminController.auth(userId).
Here is my source code,
<script type="text/javascript">
function checkboxChecked() {
var checkbox = $('td > input:checked').length;
if(checkbox == 1){
var $checked = $('td > input:checked');
var userId = $checked.parent().next().text();
** I would like to add below and make it work**
//location.href = #routes.AdmnTask.user_set(userId)
} else {
alert("Please select 1 User ID to proceed.")
}
};
</script>
After a few attempts, I noticed that I am not able to set some random variable and put into location.href as below.
var link = "#routes.AdmnTask.user_set(userId)"
location.href = link
Could anyone give me a help with this issue please?
Thank you in advance.
As I said in the comments, you can't use a Javascript variable inside a Scala function, since the Scala is executed server-side and the Javascript client-side.
There's a workaround, though.
If your #routes.AdmnTask.user_set( ... ) gives you an URL with the parameter at the end, like http://example.com/userSet/1 or http://example.com/userSet?id=1, you could create a function that transforms this URL into a more generic one :
/**
* Gets the base URL for a given route
*
* #param url Call - The route called with the parameter 0
* #return The URL base String.
*/
public static String baseUrl(play.api.mvc.Call url){
return url.toString().substring(0, url.toString().length() - 1);
}
This function will cut off the last character from your URL String, so that you can use it in your Scala template.
Then, all you need to do in your Scala / Javascript is :
location.href = '#yourClass.baseUrl(routes.AdmnTask.user_set(0))' + userId
EDIT: Here is the Scala version of the function above :
def baseUrl(url: play.api.mvc.Call): String = {
url.toString.substring(0, url.toString.length - 1)
}

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

Capture URL parameter of a link into an alert box

I want to capture the URL parameter of a link onclick and put the URL parameter in an alert box. For example clicking on the link users.php?user_id=200.
How do I capture the URL parameter "user_id=200"?
I have this script but on click, the alert box appears empty:
$(document).ready(function() {
$('.bluetext').on('click', function(event) {
var url = window.location.search.substring(1);
alert(url);
});
});
$(document).ready(function() {
$('.bluetext').on('click', function(event) {
var url = window.location.href.split("?");
alert(url[1]);
});
});
I am splitting url based on "?" question tag , which leads to "url" variable as an array having two values :
url[0] = "users.php" url[1] = "user_id=200"
And then just accessing url[1] hopes its clear now
Your script is working fine.
If you are trying to get url prameter which are re-written for example,
http://stackoverflow.com/questions/29821832/capture-url-parameter-of-a-link-into-an-alert-box/29822617#29822617
Then ofcourse you will get a blank alert msg. This is only works with non re-written urls. for example, your code will only works with this kind of url. http://stackoverflow.com/questions.php?question_id=29821832 (just for exmaple)
If you're trying to get re-written url's values then you can try following,
var params = window.location.pathname.split('/').slice(1); // ["1", "my-event"]
var first = params[0];
var second = params[1];
console.log(second) // will return "29821832". which is question id of this question.
But if you want to get non re-written url's value then your code is fine.
If you want some specific variable's value then you can try below.
I use this to get value of any variable,
function getVarVal (key) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
Call this function as per your requirement. eg.,
$('.bluetext').on('click', function(event) {
alert(getVarVal("user_id"));
});

Change url query string value using jQuery [duplicate]

This question already has answers here:
Updating existing URL querystring values with jQuery
(12 answers)
Closed 9 years ago.
I have an example URL like:
http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01
The query string contains the current page number and two additional filters (name and date).
Using the following URL parser: https://github.com/allmarkedup/purl I am able to access certain parts of the URL such as just the page number.
I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.
$(document).ready(function () {
$('.pageNum').live('keyup', function (e) {
e.preventDefault();
if (e.which == 13) {
var currentUrl = window.location.href;
var parsedUrl = $.url(currentUrl);
var currentPageNum = parsedUrl.param('page');
var newPageNum = $(this).val();
var newUrl = //
window.location.href = newUrl;
}
});
});
So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.
Is it possible to change the param value and then add it back in?
Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
purls $.params() used without a parameter will give you a key-value object of the parameters.
jQuerys $.param() will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);

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

Categories