Set query parameter based on current URL - asp.net

I am working on a standard paging component for my project. All controllers with paging are waiting for PageIndex parameter in URL.
So I want to generate URL based on the current URL except for the PageIndex parameter.
For example, I have filters for my internet store like Manufacturer and MaxPrice.
A user opens the mystore.com/products?manufacturer=Apple&MaxPrice=999 link.
Then he wants to go to the 3 pages. So the 3-page link in my paging should have the mystore.com/products?manufacturer=Apple&MaxPrice=999&PageIndex=3 link.
So needed MVC function should:
Persists all existing params like MaxPrice and manufacturer
Replace only PageIndex param
don't use any hardcoded controller and action values (like controller = 'Products', Action = 'Index')
I try to use this code:
<a class="page-link" href="#Url.RouteUrl(new { PageIndex = page })">
#page
</a>
It works fine except the 2 rule - it doesn't persist other arguments.
So if user click on this link he goes to mystore.com/products?PageIndex=3

I suggest to build the url dynamically by getting currentUrl with query strings "Request.Url.AbsoluteUri" then remove the pageIndex from url if exists , then add page index again.
hint : url must be defined as variable in your razor to make the things easier
To remove query string you can use regex
string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language"; //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");

You can use these to get the current url
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TEST/Default.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TEST/Default.aspx
And then you can add the page index like this and redirect to that url
url = url+"&PageIndex=3";
Recommended
Or you can get the url parameters with
#Url.RequestContext.RouteData.Values["manufacturer"]
#Url.RequestContext.RouteData.Values["MaxPrice"]
And use those values to build the new URL inside the View

Related

DNN rewriting URL and adding Default.aspx? in Query-String

I have a Product list page on DNN.
On this module I have a function which is called when clicked. I am adding the name of the product and SKU in the URL as a Querystring. I noticed that DNN would rewrite ?Title= to /Title/ as well as &SKU= to /SKU/ when the SKU is normal without a forward slash. For example SKU/SR2018B
The URL below would work:
www.ourwebsite.com/Product-View/Title/staple-remover-black/sku/SR2018B
My main problem is when the SKU has a special character like a forward slash, for example: SS023/10. This will cause the URL to break. I am using an encoder for the SKU. Notice that ?Title did not change to /Title/ and now there is a Default.aspx? present in the URL below.
www.ourwebsite.com/Product-View?Title/staples-2313-1000pcs-100-pages/Default.aspx?sku=SS023%2f13
Here is my Code Behind when a person is redirected to the Detailed Page.
if (tabIdToRedirectTo == null) m_alerts.ShowModuleMessage(ModuleMessage.ModuleMessageType.RedError, $"An error occurred when attempting to Redirect to the '{settingKey}' Page!", ref plcMessages, true); else Response.Redirect(Globals.NavigateURL(tabIdToRedirectTo.TabID, "", "?Title="+ hiddendescription.Value + "&sku=" + HttpUtility.UrlEncode(hiddensku.Value), EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)));
I believe it's how you're calling the Globals.NavigateUrl function. The call takes a params of strings which are your query strings in the key=value format. I usually like to easily see what I am about to pass so I do something like the following:
var qsParams = new List<string>{
"Title=" + hiddendescription.Value, // "Title=staples-2313-1000pcs-100-pages"
"sku=" + HttpUtility.UrlEncode(hiddensku.Value), // "sku=SS023%2f13"
EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)
};
return Globals.NavigateURL(tabIdToRedirectTo.TabID, "", qsParams.ToArray());
Granted - I do not know what your EmbeddedModule.GenerateFullQueryStringForEmbedding does, but as long as it returns a key=value type output, it should be passed and processed well.

Get string from current URL

I am writing an asp.net MVC Application. I have the application send a request to FreeAgent and if the request is successful a code is returned in the redirect of the URL.
For example this is a copy of a successful URL.
{
http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=
}
They have added the ?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state= to my URL
I need the bit after the ?code= and before &state=
I can use this to get the URL
string code = Request.Url.AbsoluteUri;
but I need help extracting the code from this
edit:
The code will be different each time it is run
You can use the System.Uri and System.Web.HttpUtility classes
string uri = "http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=";
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
Then the value of the code query parameter will be available in queryDictionary["code"]

How to get Tridion item ID after created using Core Service

I am creating a new item using the Core Service in this post. However, the URI of the newly created item is tcm:0-0-0 instead of the actual TCM URI. the Title property is correct (and not New Component) but the WebDav path returns 'New Component' while .
What is the best way to get the URI of my newly created item?
client.Create(newComponent, null);
string newItemUri = newComponent.Id; // returns tcm:0-0-0
string webDavUrl = newComponent.LocationInfo.WebDavUrl; // returns New%20Component
string title = newComponent.Title; // correct
Second parameter of Create method are ReadOptions. They are used to specify how the item will be read back. In your example you have it set to null, meaning you will not read it back. What you should do is set ReadOptions and assign item read back to a variable, like this:
newComponent = (ComponentData) client.Create(newComponent, new ReadOptions());
Check out Ryan's code at http://blog.building-blocks.com/uploading-images-using-the-core-service-in-sdl-tridion-2011. He uses client.Save to get the saved Component, from which he's able to access the ID.

ASP.NET 4.0 URL routing with two or multiple querystring parameters

How can I pass two querysting parameters in URL routing using ASP.NET 4.0?
I have gone through many articles, but everywhere it shows only one parameter.
I'd like the display URL to be:
http://www.mywebsite.com/reports/1-this-is-my-first-report
The first parameter is ID: 1
The second is Name: This is my first report
I am trying following route, but it is not working
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}-{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
How can I make this work as described?
Try formatting the URL this way:
http://www.mywebsite.com/reports/1/this-is-my-first-report
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}/{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
Try this
Response.RedirectToRoute("UrlRouting for Querystring",
new { name = txtsearchurlrouting.Text, text = txtsearchid.Text });
In Global.asax
routes.MapPageRoute("UrlRouting for Querystring",
"Querystring/Selected/{name}/{text}/", "~/Address.aspx");
like this we can pass multiple querystring parameters

ASP.NET & Ajax: query string parameters using ISO-8859-1 encoding

Here's another one for you to help me solve: I have an ASP.NET website that uses AJAX (asynchronous) calls to am .ashx handler, passing a query string parameter to get some information from the database.
Here's an example of how it works:
Client-side (Javascript) code snippet that makes the asynchronous call to the handler:
/* Capture selected value from a DropDownBox */
var dropdown = document.getElementById(DropDownID);
var selectedValue = dropdown.options[dropdown.selectedIndex].value;
/* Make the call to the handler */
var url = "MyHandler.ashx?param=" + selectedValue;
var ajaxObj = new Ajax();
ajaxObj.doRequest(url, MyCallback, args, connectionFailed);
When I load the webform (that contains this AJAX call) for the first time, it sends the right query string to the handler (I checked it using debug in Visual Studio), like param = Street Joseph Blíss. That's the right behavior I want it to have.
The thing is that when I load that webform again (and all subsequent times), that í character from "Blíss" appears in server-side as í-. As that's the key from the entity I'm trying to select on server-side database access script, it doesn't work as it worked on 1st webform load.
I tried encoding the query string on client-side and decoding it on server-side, using something like this:
Client-side (Javascript):
var encodedParam = encodeURIComponent(selectedValue);
/* Make the call to the handler */
var url = "MyHandler.ashx?param=" + encodedParam ;
Server-side (ASP.NET, C#):
string encodedParam = context.Request.QueryString["param"];
string value = HttpUtility.UrlDecode(encodedParam, Encoding.ASCII);
...but I had no luck with it and the problem still remains. Any help?
After some more searching, I found out how to solve with server-side code refinement. Here's the deal:
I had to alter my .ashx handler to parse the original parameter grabbed from the query string and convert it into UTF-8. Here's how it's made:
// original parameterized value with invalid characters
string paramQs = context.Request.QueryString["param"];
// correct parsed value from query string parameter
string param = Encoding.UTF8.GetString(Encoding.GetEncoding("iso8859-1").GetBytes(paramQs));
Happy coding, folks! :)

Resources