Replace Query String of a page - c#

I want to replace the Query String of my page like this-
firstly I move to this page on clicking on menu bar Items by setting this URL-
Response.Redirect("SearchtWorkForceReport.aspx?page=Search");
then I want to change url like this-
"SearchtWorkForceReport.aspx?page=Search" to "SearchtWorkForceReport.aspx?page=Edit" on a check box change event.
I try this code-
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("page"))
{
strQueryString = strQueryString.Replace("Search", "Edit");
}
and it'll replace the Query String but on page load if I get the query string should give again the previous set string.
type = Request.QueryString["page"].ToString();

You can't edit query string of the page by editing Request.QueryString. you should redirect to current page. use code below:
if (Request.RawUrl.Contains("page"))
{
Response.Redirect(Request.RawUrl.Replace("Search", "Edit"))
}

Query strings are provided by your clients, changing your copy server-side does not have any effect.
You have to redirect your client to the new URL with the new query string:
Response.Redirect("SearchtWorkForceReport.aspx?page=Edit");

From your question my understanding is you are trying to change the query string in check box change event on the second page.
so write this code in checkbox change event
Response.Redirect("SearchtWorkForceReport.aspx?page=Edit");
and in page load check the querystring
string type = Request.QueryString["page"].ToString();
if(type=="Edit")
{
//what you want to do?
}

Related

how to make cookie in asp.net that takes url query string

intern in company working with asp.net and sitecore here
My very first assignment has to do with adding support for a query parameter that can will enable the editor to see some key names of some buttons for a page.
Now i was thinking that i would make a cookie with httpcookie in the correct controller and somehow get the query parameter into the cookie, could that be done in a way?
many thanks?
You can use a URL querystring parameter to get the value you need on Page Load and then set controls accordingly. As for storing Values you can store whatever you need in ViewState or SessionState and look them up when you need to.
Example below:
private void Page_Load()
{
if(Request.QueryString["switch"] !== null)
{
if(Request.QueryString["switch"].ToString()) == "on")
{
button.Visible = true;
ViewState["someval"] = hiddenVal.Text;
}
else
{
button.Visible = false;
}
}
}

I want to get the url of the webpage which is loading after clicking a button

here I am getting the url of the previous page.
LookUpDict.driver.FindElementByXPath("//*[#id='ns__30899058_jsel_div1_contextMenu_alertsdijit_Menu_5_menuItem_1_CreateTicket_ProxyHFC']").Click();
String ticketUrl = LookUpDict.driver.Url;
LookUpDict.driver.Navigate().GoToUrl(ticketUrl);
public void CurrentUrl() {
String pURL = driver.getCurrentUrl();
driver.findElement(By.xpath(“<xpath>“)).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
String cURL = driver.getCurrentUrl();
if(pURL!= return){
System.out.println(cURL);
}
else{
System.out.println(“No new URl”);
}
}
You are getting the URL after the click which is after the navigate happens. If you want to get the URL before the navigation/click you need to rearrange your code.
String ticketUrl = LookUpDict.driver.Url;
LookUpDict.driver.FindElementByXPath("//*[#id='ns__30899058_jsel_div1_contextMenu_alertsdijit_Menu_5_menuItem_1_CreateTicket_ProxyHFC']").Click();
LookUpDict.driver.Navigate().GoToUrl(ticketUrl);
You can also just use Driver.Navigate().Back(); to avoid having to store the previous URL.

Selenium entering invalid text (Half text) in text box

While running multiple test cases, selenium is entering invalid text as shown in the attachment.
Below are the two Examples showing the error:
Instead of entering AutomationTest123_6035633258972, it just enters 6035633258972. .
Instead of Entering AutomationTest123_636010703068635512, it just
enters utomationTest123_636010703068635512. .
Code
//StaticVariable is class which has static values
var username = StaticVariable.username;
var password = StaticVariable.password;
driver.FindElement(By.Id("username")).SendKeys(username); //putting wrong values
driver.FindElement(By.Id("password")).SendKeys(password); //putting wrong values
driver.FindElement(By.Id("login")).Click();
Can anyone help me on this? Any help would appreciated.
first of all make sure that
var username = StaticVariable.username;
is assigning the right value.
use a
print
to check what the value of username after assign.
than try by using the below code:
driver.FindElement(By.Id("username")).click()
driver.FindElement(By.Id("username")).clear()
driver.FindElement(By.Id("username")).SendKeys(username);
There can be a couple of reasons I've seen that this can be an issue. I'd first try to clear out the text input first and make sure it has focus.
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
userElem.click();
userElem.clear();
userElem.sendKeys(userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
passElem.click();
passElem.clear();
passElem.sendKeys(password);
// Click login button
driver.findElement(By.id("login"))
.click();
If, however, that doesn't fix it, I've had situations where splitting the string up and sending keys a few at a time has worked. That does have a performance penalty so I wouldn't do it unless you really really need to.
public void fooTest() {
// Do stuff to get to the correct page, etc
var username = StaticVariable.username;
var password = StaticVariable.password;
// Fill out user name
var userElem = driver.findElement(By.id("username"));
sendKeys(userElem, userName);
// Fill out password
var passElem = driver.findElement(By.id("password"));
sendKeys(passElem, password);
// Click login button
driver.findElement(By.id("login"))
.click();
// do assertions, etc
}
private void sendKeys(WebElement elem, String keys) {
elem.click();
elem.clear();
for (int i = 0; i < keys.length(); i) {
elem.sendKeys(keys.charAt(i));
}
}
Note : sorry for any syntax / c# errors, I've barely used the language ... I'm much more familiar with Java ;-)
Use the clear method then type the text: driver.findElement(By.cssSelector("").clear();
It may help.
Rather than using 'var' , you might want to try putting in the specific type , such as 'string'. The problem has to be in what is being passed to .SendKeys() or how it is being received by the function.
string username = StaticVariable.username;
string password = StaticVariable.password;

How to update querystring in C#?

Somewhere in the url there is a &sortBy=6 . How do I update this to &sortBy=4 or &sortBy=2 on a button click? Do I need to write custom string functions to create the correct redirect url?
If I just need to append a query string variable I would do
string completeUrl = HttpContext.Current.Request.Url.AbsoluteUri + "&" + ...
Response.Redirect(completeUrl);
But what I want to do is modify an existing querystring variable.
To modify an existing QueryString value use this approach:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly
I go into more detail in another response.
Retrieve the querystring of sortby, then perform string replace on the full Url as follow:
string sUrl = *retrieve the required complete url*
string sCurrentValue = Request.QueryString["sortby"];
sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue);
Let me know how it goes :)
Good luck
private void UpdateQueryString(string queryString, string value)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Set(queryString, value);
isreadonly.SetValue(this.Request.QueryString, true, null);
}
If you really want this you need to redirect to new same page with changed query string as already people answered. This will again load your page,loading page again just for changing querystring that is not good practice.
But Why do you need this?
If you want to change the value of sortBy from 6 to 4 to use everywhere in the application, my suggession is to store the value of query string into some variable or view state and use that view state everywhere.
For e.g.
in Page_Load you can write
if (!IsPostBack)
{
ViewState["SortBy"] = Request.QueryString["sortBy"];
}
and everywhere else ( even after postback ) you can use ViewState["SortBy"]
Based on Ahmad Solution I have created following Method that can be used generally
private string ModifyQueryStringValue(string p_Name, string p_NewValue)
{
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set(p_Name, p_NewValue);
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
return url + updatedQueryString;
}
and then us it as follows
Response.Redirect(ModifyQueryStringValue("SortBy","4"));
You need to redirect to a new URL. If you need to do some work on the server before redirecting there you need to use Response.Redirect(...) in your code. If you do not need to do work on the server just use HyperLink and render it in advance.
If you are asking about constructing the actual URL I am not aware of any built-in functions that can do the job. You can use constants for your Paths and QueryString arguments to avoid repeating them all over your code.
The UriBuilder can help you building the URL but not the query string
You can do it clientside with some javascript to build the query string and redirect the page using windows.open.
Otherwise you can use Response.Redirect or Server.Transfer on the server-side.
SolrNet has some very helpful Url extension methods. http://code.google.com/p/solrnet/source/browse/trunk/SampleSolrApp/Helpers/UrlHelperExtensions.cs?r=512
/// <summary>
/// Sets/changes an url's query string parameter.
/// </summary>
/// <param name="helper"></param>
/// <param name="url">URL to process</param>
/// <param name="key">Query string parameter key to set/change</param>
/// <param name="value">Query string parameter value</param>
/// <returns>Resulting URL</returns>
public static string SetParameter(this UrlHelper helper, string url, string key, string value) {
return helper.SetParameters(url, new Dictionary<string, object> {
{key, value}
});
}
The only way you have to change the QueryString is to redirect to the same page with the new QueryString:
Response.Redirect("YourPage.aspx?&sortBy=4")
http://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.100).aspx
I think you could perform a replacement of the query string in the following fashion on your server side code.
NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("SortBy");
filtered.Add("SortBy","4");
The query string is passed TO the server. You can deal with the query string as a string all you like - but it won't do anything until the page is ready to read it again (i.e. sent back to the server). So if you're asking how to deal with the value of a query string you just simply access it Request.QueryString["key"]. If you're wanting this 'change' in query string to be considered by the server you just need to effectively reload the page with the new value. So construct the url again page.aspx?id=30 for example, and pass this into a redirect method.

How to build a elegant customized URL

i am working on a dashboard page where user will have a multiple choices to select properties and based on the selected properties it will generatea final URL and render.
so let say i have 10 different proprites:
ShowImage=true/false
ShowWindow=true/false
ShowAdmin = true/false
ShowAccounts = true/false
.............
..........
...........
my URL will be static which will be hitting the produciton so there is no change in terms of HOSTNAME.
so here is what i come-up with:
const string URL = "http://www.hostname.com/cont.aspx?id={0}&link={1}&link={2}........";
string.Format(URL, "123","aaa123", "123"............);
but the problem with the above solution is that, regardless it will generate me a long url whether i select or not...
any optimized solution?
You could use the StringBuilder class (System.Text namespace):
StringBuilder sbUrl = new StringBuilder();
sbUrl.AppendFormat("http://www.hostname.com/cont.aspx?id={0}", 123);
if (ShowImage) {
sbUrl.AppendFormat("&link1={0}", "aaa123");
}
if (ShowWindow) {
sbUrl.AppendFormat("&link2={0}", "aaa123");
}
string url = sbUrl.ToString();

Categories