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.
Related
User input the url string in a textbox and I need to add a string "cmd" if not available .
Please suggest how to achieve this,
string cmdUrl = AddPrefix("https://google.com");
static string AddPrefix(string inputUrl)
{
return formattedUrl;// want to return https://cmd.google.com if the string cmd not added already in url
}
First, you can parse your url using var parsedUrl = new Uri(inputUrl).
Then check if the host includes your substring like this: parsedUrl.Host.StartsWith("cmd")
If it does, return your original url else build your new one: $"{parsedUrl.Scheme}://cmd.{parsedUrl.Host}{parsedUrl.PathAndQuery}"
I'm trying to retrieve the URL of the current page via a Web Method. The code below works well on a normal C# Method such as the Page_Load but does not work inside a Web Method.
[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
string project_id = HttpContext.Current.Request.Url.ToString();
}
I'm receiving an empty string ("") as the project_id. What am I doing wrong?
You need this:
[WebMethod]
public static string mywebmethod()
{
string myUrl= HttpContext.Current.Request.UrlReferrer.PathAndQuery.ToString();
return parameters
}
Try to do next code:
[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
string project_id = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
}
Url is just object, that's why it returns empty value to you. AbsoluteUri will give a full URL of current page. Example: http://yourweb.site/Admin.aspx?id=15&time=yesterday
To get information of the client's previews request to current website you can use the UrlReferrer as follow:
//To get the Absolute path of the URI use this
string myPreviousAbsolutePath = Page.Request.UrlReferrer.AbsolutePath;
//To get the Path and Query of the URI use this
string myPreviousPathAndQuery = Page.Request.UrlReferrer.PathAndQuery;
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?
}
In the application I am working on, we allow user to enter a list of domain names, we expect the user to enter the domain names in any on the following formats
stackoverflow.com
www.stackoverflow.com
http://stackoverflow.com
http://www.stackoverflow.com
but when storing this domain names back into our databases, we want to store the domain name in the following format only
Format : stackoverflow.com
So wanted to know if there is a ready made helper that I can use to get this job done, or any suggestions to do this in an efficient manner.
What have I tried ?
This is what I came up with,
public static string CleanDomainName(string domain)
{
domain = domain.Trim();
if (domain.Split('.').Count() > 2)
{
domain = domain.Split('.')[1] + "." + domain.Split('.')[2];
}
return domain;
}
Please help me out on this.
use Regex to replace the expressions in the beginning of the string:
Regex.Replace(input, #"^(?:http(?:s)?://)?(?:www(?:[0-9]+)?\.)?", string.Empty, RegexOptions.IgnoreCase);
this will replace:
an eventual "http://" in the beginning (or "https://") followed by
an eventual "www." (also with a number following ie: www8 or www23)
Use the Uri class.
string url = "http://www.testsite.com/path/file.html";
Uri uri = new Uri(url);
There are various properties do retrieve different parts of the url.
Use uri.Host to get the www.testsite.com portion of the url. A little string manipulation can remove the www.;
string domain = uri.Host;
if (domain.StartsWith("www."))
{
domain = domain.Substring(4);
}
Use the System.Uri class.
System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
string uriWithoutScheme = uri.Host.Replace("www.","") + uri.PathAndQuery;
This will give you: stackoverflow.com/search?q=something
public static string CleanDomainName(string url)
{
var uri = url.Contains("http://") ? new Uri(url) : new Uri("http://" + url);
var parts = uri.Host.Split('.');
return string.Join(".", parts.Skip(parts.Length - 2));
}
/// <summary>
/// Clears the sub domains from a URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>String for a URL without any subdomains</returns>
private static string ClearUrlSubDomains(Uri url)
{
var host = url.Host.ToLowerInvariant();
if (host.LastIndexOf('.') != host.IndexOf('.'))
{
host = host.Remove(0, host.IndexOf('.') + 1); // Strip out the subdomain (i.e. remove en-gb or www etc)
}
return host;
}
You can create a new Uri from your domain so calling it will be:
ClearUrlSubDomains(new Uri(domain))
This doesn't address urls like http://www.something.somethingelse.com but can be modified to do so with a while construct of equivalent.
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();