Should I still use querystrings for page number, etc, when using ASP.NET 4 URL Routing? - webforms

I switched from Intelligencia's UrlRewriter to the new web forms routing in ASP.NET 4.0. I have it working great for basic pages, however, in my e-commerce site, when browsing category pages, I previously used querystrings that were built into my pager control to control paging and now am not sure how to handle this using routing.
I defined a MapPageRoute as:
routes.MapPageRoute("cat-browse", "Category/{name}_{id}", ~/CategoryPage.aspx");
This works great. Now, somebody clicks to go to page 2. Previously I would have just tacked on ?page=2 to the url. How do I handle this using web forms routing? I know I can do something like:
http://www.mysite.com/Category/Arts-and-Crafts_17/page/2
But in addition to page, I can have filters, age ranges, gender, etc.
Should I just keep defining routes
that handle these variables like
above?
Should I continue using querystrings
and if so, how do you define a route
to handle that?

The main reason to use url routing is to expose clean, user-and-SEO-friendly, URLs. If this is your goal, then try to stick to it and not use querystring parameters. Note: I don't believe we need to completely ban the use of querystrings and, depending on your situation, you may decide it best to use querystring parameters for parameters that are not used frequently, or where no real value is added by making the information more semantically meaningful.
So here's what I would do:
Define a catch-all for all your other parameters:
routes.MapPageRoute("cat-browse", "Category/{name}_{id}/{*queryvalues}", "~/CategoryPage.aspx");
In /CategoryPage.aspx, access the router parameter and then parse as appropriate:
Page.RouteData.Values["queryvalues"]
Instead of using the syntax of Arts-and-Crafts_17/**page/2/age/34** for these parameters, I perfer to use the following syntax: Arts-and-Crafts_17/pg-2/age-34/
If you do this, the catch-all parameter 'querystring', will equal pg-2/age-34. You can now easily parse this data and add each name/value to the page context. Note that you will need to do something along these lines since each of these parameters are optional on your site.

You can take advantage of C# 4.0 named and optional parameters. Please have a look at this example from haacked
If you are using a lower version of the framework, you can also use code from the link above. But instead of declaring the method as
public ActionResult Search(int? page=0)
{}
you can declare it as
public ActionResult Search(int? page)
{
if(page == null)
{
page=0;
}
}
HTH

Related

Calling a controller/action through query parameters

Is it possible to call a controller and action directly by using query parameters in Laravel? I see some frameworks allow /index.php?_controller=X&_action=Y, or Yii allows /index.php?r=X/Y. I was wondering if something similar was possible in Laravel/Symfony.
symfony
The query string of a URL is not considered when matching routes. In this example, URLs like /blog?foo=bar and /blog?foo=bar&bar=foo will also match the blog_list route.
https://symfony.com/doc/6.0/routing.html
laravel afaik doesnt support that either
you are obviously free to just forward yourself
e.g. write one router that forwards to other controllers
symfony https://symfony.com/doc/6.1/controller/forwarding.html

Asp.Net Web Api - Change parameter name

In my team we have coding rule that requires that every function's parameter starts with prefix, e.g. *p_someParam*.
With Web Api if we want to request a GET function that takes two parameters, we should add those parameters like "...?p_firstParam=value1&p_secondParam=value2".
Is there some way to use in requests more user-friendly names, like someParam without prefix, that will automatically map to parameters in controller's action? Maybe there is some attribute to rename action parameters? I couldn't find any similar example.
Every clue is appreciated.
I think you looking for URL rewriting, in that you need to map the urls to config or programmatic
http://www.codeproject.com/Articles/2538/URL-Rewriting-with-ASP-NET nice article to follow, its in ASP.Net,

Passing multiple values as query string is good or bad practice in MVC

In my page I ve to pass multiple values to controller.
My URL looks something like :
http://blah/Search/Page/?type=new&keywords=blahblah&sortType=Date
Is Passing multiple values as query string good practice in MVC ? or We can have slash separated URL, by using introducing custom routing?
NB: Lets consider all the values in my query string, are not secure / sensitive data.
I wouldn't consider it a bad practice, as long as it's not senstive data. It just depends if you want to write a custom route in your global.asax to handle it or not. The custom routes provide a cleaner url forsure. Also, for more savy users if they understand the concept on your site, it's more intuitive.
So consider this:
http://baseballcards/topps/1980 // search for baseball cards made by topps in the 1980s
http://recipes/deserts/pies // search for a desert recipe that are pies
http://code/csharpe/linq // search for csharp code that has linq examples
In these examples we can almost read the url like a sentence, making it more intuitive, giving a user the ability to plug and play. It clearly denotes the query almost like a breadcrumb, indicating exactly what the context will be. I personally like this. But either way is a good approach.
To extend with more parameters:
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
Some examples:
Search/Recipes/Deserts/Pie
Search/Recipes/Dinner/Beef
Search/Recipes/Lunch/Salads
Select later (query string in route values) in case,
If you are concerned about header length.( By default get parameters are part of headers, and web server accept 1024 byte header length by default in IIS7).
Hide logical implementation of your code.
Url looks good and easier to remember.
Otherwise Both the approaches work equally.
I think passing search parameters in the query string is the way you should go, especially if all your parameters are optional. It also enables you to use normal method="get" forms without hassle.
I don't think "security/personal data" has anything to do with this since the query string is a part of the URL just like the path is.
IMO I think this is absolutely fine. I think it is actually preferable to use querystrings in MVC when the path represents the function and the querystring parameters represent the filters, e.g. as in a search.
However, I wouldn't use querystring parameters for data that represent information about the content retrieved. So I would include the year and month of an article in the path but not the page number if returning more than one page of articles for the year and month.

What are the benefits of using MVC HTML helpers like ActionLink, BeginForm, TextBox, etc instead of the native HTML tags?

In a SO response to a different question, a user stated that it allowed you to avoid hard-coding route values into a html link tag, but that is not really valid since you have to put in the controller, action, area, etc as strings so you are still hard-coding the route values.
How is this:
#Html.ActionLink(linkText: "MyLink", actionName: "MyAction", controllerName: "MyController", new { id = #myId }, new { area = "SomeArea"})
better than this:
<a href='/SomeArea/MyController/MyAction/myId'>MyLink</a>
Your observation is only true if (a) you're using strictly the default routing format and (b) if your application will always be installed at the root of the site. If you don't do the former (say create a short cut route /help which goes to the Home controller and Help action, and subsequently change it by introducing a Help controller with more actions, then you'll need to update all of your hard-coded anchor tags. A better alternative is using the RouteLink helper with the route name and, optionally, other parameters.
With regard to the latter, I typically use a single server for most of my staging deployments and the application does NOT sit at the site root, but rather in a subdirectory. Production deployment is mixed, but many applications get installed at the site root. Using the helpers allows me to ignore the difference during development as the helper properly constructs the url relative to the current site in all cases. This is so helpful that I even use it for scripts, css files, images, etc. via the UrlHelper to make sure that any paths specified for those do not break between staging and production.
There seems to be little to benefit in using the helper, providing you make one change - add a tilda so that the router automatically resolves the address to the correct place.
<a href='~/SomeArea/MyController/MyAction/myId'>MyLink</a>

Getting the url of an aspx page using the page type

I'm using a web application project.
I have a folder in my web root called Users and in the folder I have a page called UserList.aspx
What I want to be able to do is type in Response.Redirect(Users.UserList.URL)
What I reckon I can probably do is create a class that extends Page and add a static property called URL that calls MethodInfo.GetCurrentMethod().ReflectedType (I think this works haven't tested) and then have that convert Users.UserList -> ~/Users/UserList.aspx
The problems with this method that I know of are one I need to go through every page and make it extend the base class and it doesn't work with any pages that contain a '-' character.
The advantages are that if pages are moved around then there aren't any broken links (Resharper gives out when there is a Page with the wrong namespace).
Also then every individual page that takes query string params could have a static method so that if I want to add/remove params I can see what uses those params etc.
Also if I want to call that page I don't have to check the name of the params e.g. UserId userId, Id or id. So that would look something like Users.ViewUser.GetUrl(1) -> ~/Users/ViewUser.aspx?UserId=1
So the question is: Is there a better way of doing this? Or is this a bad idea in principal?
You could just create an extension method for the base Page class that does what you are thinking. That would avoid having to go back and modify the base class for all your pages.
There is a better way. Create a traffic cop that knows about paths. Then if paths change, your data model changes or other stuff you just change that one place. Plus you could have read from a config file and make changes at run time.
Thus your call looks like this:
Repose.Redirect(TrafficCop["Users.UserList"].URL)
or some other way if you don't like the syntax.
The MethodInfo.GetCurrentMethod().ReflectedType doesn't work so I came up with another method of doing this using generics.
Instead of Users.ViewUser.GetUrl() or Users.ViewUser.URL it's GetUrl()
For a page with parameters it's still Users.ViewUser.GetUrl(1), it isn't ideal because they should both have the same way of being called but better than strings I guess.
Going to leave the question open for a while just in case.
edidt: I think I will actually just create another method called GetUrl(String getQuery) because if I have two parameters that are of the same type it doesn't work very well.
further edit: I found out how to do exactly what I want to do.
created a class called BasePage:Page where T : Page
on that are the static methods redirect and geturl
each page inherits from the base page as follows: MyPage:BasePage
Any page can redirect to that page by using the command MyPage.Redirect();

Resources