I am trying to use slugs in an MVC web application but can seem to work out the best way to implement them.
I have found the the recommendation on how to create the URL friendly slug stackoverflow slug post
I still want to be able to query the Db with the ID but don't want this to be in the URL similarly to most stackoverflow URLs, for example
http://website/home/list/outdoor-products
How can a slug be displayed in the URL while still passing and using an ID to be used to query with?
It's doesn't really depends on a technology/framework which you are using, the main thing is you have to have destinctive urls to unambiguously select page content.
If you do have unique titles/slugs for pages, then you may use them as identity for content selection. Otherwise, you need to put some sort of id (it could be int or guid, whatever) into your urls. There isn't anything which will hide your int id behind the slug.
Talking about stakoverflow's urls, you'll find id just before the friendly title. Another option could be put actual id at the end of friendly title (friendly-title-1559063).
Related
I have two views and two controllers. One for clients and the other for their addresses. Clients can have one address. In my model definition for client I allow the addressID of the client to be nullable. When I want to create an address for a client, according to the addressId being null or not i will redirect to either the address's "create" or "details" view. For now I want to just display the clients name when I reach the Create view("creating address for John Doe"). How do i go about doing this? I'm trying to learn MVC slowly and I'm having trouble dealing with the separation of concerns and where to pass data.
Since you are redirecting manually you know the next request for sure. In this case TempData may fit your needs best. If you need the data for more than the next request you should probably use Session or Cookies as already suggested.
Use this to store data for the next request:
TempData["ClientName"] = "John Doe";
And this to get the data out in the next request:
var clientName = TempData["ClientName"];
Please note that TempData stores its data only for the next request. For further info about TempData MSDN is your friend: http://msdn.microsoft.com/en-us/library/dd394711%28v=vs.100%29.aspx
Try to put some code for others to help you better, but for now what I can tell you is that you want to keep state across requests, therefore you have many options. You can keep a session state, you can have a querystring appended to your following requests, you can have cookies transporting the id, etc.
I would recommend you using session for this .. store the username is session("username") and use it in view or in any controller u want ..
I have a main page with a large list of companies, I have a search button and if I want to find a company by state or city I can filter my search.
I decide to filter my search by cities, lets say Chicago, and I get 10 companies as a result of my search.
I click any company in that list and I go to the company details but I realize that is not the one I am looking for, so I want to go back to my 10 companies result list but instead I go back to the main company search interface and I have to re-start my search again.
How to use a session variable or cookies for this case?
Somebody can help me with this?
Another valid option not involving Session or cookies would be using the url for passing search parameters. If your site is public this may also help you with SEO.
You could use a friendly url + rewriting rules or just querystring if you are not using any rewriting.
On the company details page you'd store the referrer url and if the user wants to come back, you do it to that page.
I agree with Claudio, but if you do want to use session I would do something like the following
In page load do something like this
if(!Page.IsPostBack)
{
string filter = Session["SearchQuery"].ToString();
if(filter != null)
{
FilterResults(filter)
}
}
And then in your filter event do something like
Session["Filter"] = txtCityName.txt;
FilterResults(txtCityName.txt);
I am working with URL rewriting, and have some issues. I want my url to be like this:
www.domain.com/product/myproduct
But I also want to be able to retrieve the ID of the product, without accessing the database. I thought about having a URL like:
www.domain.com/product/myproduct/1
or
www.domain.com/product/1-myproduct
But if I could hide the ID it would be better.
So, how do I do it the simplest way?
Currently my Global.asax has the following route:
routes.MapPageRoute("Produkt visning",
"legetoej/{Categoryname}/{SubCategoryname}/{ProductName}",
"~/SingleProduct.aspx");
And when I retrieve the name I do like this on SIngleProduct.aspx:
object productRoute = Page.RouteData.Values["ProductName"];
if (productRoute != null && !string.IsNullOrEmpty(productRoute.ToString()))
{
// do stuff
}
If I very simple could just get the ID instead of name, it would be awesome.
Thanks a lot awesome-stackoveflowers ;-)
To hide the ID of the Product... take the ID and apply Encryption to it... something like DES or Triple DES, then apply Server.URLEncode method to the ID and then you can easlily hide the id.
When you open the Page you can simple take the encrypted ID and do a Server.URLDecode and the decrypt the ID.
Anyways... why dont you pass the ID of the product as a get Parameter ? Something like...
www.domain.com/product/myproduct?PID=#$$#12 , where the PID is encrypted and URL Encoded and then you can easily process it.
I don't know how to ask this, and I don't know what it is called either so I'll just describe what I want to achieve.
In the database, some articles' title originaly has spaces:
my title with spaces
But in the url, spaces are replaced by other characters such as plus sign (+) or underscore (_)
http://www.mydomain.com/mycontroller/myaction/my_title_with_spaces
or
http://www.mydomain.com/mycontroller/myaction/my+title+with+spaces
Now, how do you do that in C#? Or is there any helper in ASP.NET MVC that can do something like that?
Let say we achieved the said URL, is there any risk that two unique titles become the same in the URL? Please consider these titles:
Title's
Titles
after parsing, they became the same
Titles
Titles
This will be a problem when retrieving the article from the database since I'll get two results, one for "Title" and one for "Title's".
I would implement that functionality like this:
1. When creating a new article, generate the URL representation based on the title.
Use a function that converts the title for a suitable representation.
For example, the title "This is an example" might generate something like "This_is_an_example".
This is up to you. You can create a function that parses the title with rules you define, or use an existing one if it suits better your problem.
2. Ensure the URL representation is unique
If it's going to be an ID, it must be unique. So, when creating new articles you must query your database for the resulting URL representation. If you get a result from the database, it means the newly created article generated the same representation as one of the already created articles. Add something to it so it remains unique.
This could be something like "This_is_an_example_2". In this case, we added the "_2" to the end of the generated representation so it differs from the already existing one. Once more, with each change you have to ensure this representation remains unique.
3. Save the created ID in the database, along with the article data
In the database be sure to save the "This_is_an_example" ID and relate it to the article. Maybe even as the table primary key?
4. Query the database for the correct article
Now, about showing a site visitor the correct article:
When a visitor asks for the following resource, for example:
http://www.mydomain.com/mycontroller/myaction/this_is_an_example_2
Extract the URL part that identifies the article, in this case "this_is_an_example_2".
When you have that, you have the identifier of the article in the database. So, you can query the database for the article with the "this_is_an_example_2" ID and show the article's content to the user.
This might involve some URL rewriting. Unfortunately I'm unable to help you with that in asp.NET. Some search on the subject will surely help you.
Web pages have moved to use URLs like:
//weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
i.e. they include the title of the page in the url rather than having some coded id.
I understand that this is useful for SEO, and also for users in finding the correct page where they wish to type in the url.
I would like to follow this approach, but wonder how best to acheive it, and particularly how to deal with duplicates.
Is a database trigger which creates the url based on the title and adds a numeric incremental suffix to any duplicates the best way to go, and if so what would such a trigger look like?
Instead of having an id based on a title they could use id based on both a date and a title (2007/12/03/asp-net-mvc-framework-part-2-url-routing). So if you don't have articles with the same titles in one day (which isn't too severe restriction) duplicates are eliminated.
In Wordpress at least, the "slug" (as they call it) is generated once from the item's title and stored separately in the database. If two "slugs" collide, it appends -1, -2, etc. to the end. I personally prefer if you add an (optional) field to the submission form to allow people to insert their own—it allows people to specify a shorter URL than my-long-article-is-hard-to-type.
You've got to model this concept in your application. URL generation based on title can be automatic, but it can't be invisible. WordPress (and probably other CMS's, too) do a pretty good job of this -- they'll default a URL based on the information you enter, but the "key" part of the URL is visible and editable to the user, and uniqueness is enforced at the appropriate level (globally, per month, per day -- whatever).
Making URL generation completely invisible will lead to confusing errors for the user, I believe.
You could do the same thing that SO does. That is, the slug is only there as GoogleJuice. These two URLs resolve to the same thing:
ASP.Net MVC - route object id == title - how to deal with duplicates?
ASP.Net MVC - route object id == title - how to deal with duplicates?
So, in the example you gave, if the CMS gave each post a unique numeric identifier (which I suppose is quite likely) then you can include it in the URL:
http://weblogs.asp.net/scottgu/archive/2007/12/03/1234/asp-net-mvc-framework-part-2-url-routing
In this example, the symbol 1234 is the post's identifier.