0

I have a DirectoryController with an Index() ViewResult which displays the following links in the view:

@Html.ActionLink("My file 1", "Index", "File", new { @id = "123" }, null) <br />
@Html.ActionLink("My file 2", "Index", "File", new { @id = "456" }, null) <br />
@Html.ActionLink("My file 3", "Index", "File", new { @id = "789" }, null) <br />

If I click on one of the links, I’ll end up having (for example) the following in the URL:

http://www.domain.com/File/Index/123

What I’d really like to have is the following in the URL:

http://www.domain.com/File/my-file-1

Basically, I’d like to see the Controller name and a custom name (the name of the file for example) in the URL without showing the actual action or the id.

Regardless of the link I click, all of them should continue to point to the Index() method of the FileController passing along the appropriate id.

How would I go about this?

How and what kind of custom route should I create?

Thanks

1
  • When displaying filenames as part of the route, make sure you have no special characters in your filenames, such as %. Though they will get converted in your URL, unlike QueryString paramters, they will crash the call as they can't be parsed by the routing. For more details on that particular issue see my answer as well as another post I linked there in this post here: stackoverflow.com/questions/9123203/… Commented Feb 17, 2012 at 17:44

2 Answers 2

1

As general overview:

what you want to do is create route mapping

eg translating url that is user friendly

you would need to do some updates in your controller/ global.asax

example of route

  context.MapRoute(
              "FileNameMapping",
              "File/{filename}",
              new {controller="File", action = "Index" });

in your action you will have something like

Public FileResult Index(string filename){
// do your logic for handleling file name 
//and return file
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the info. I’ve added your route above the default one in the Global. When clicking my links, I still get the same behavior. I still get normal url…Controller/Action/Id. What am I missing in order to get Controller/custom-name which in turn would bring me to my Index() method passing along the id param?
@Vince: While reading your question, can you identify from the name the id?
0

In case you'll be running this on IIS, rather than Casini, you can use URL re-writes to achieve the desired result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.