views:

103

answers:

2

Hi All,

I have a catch-all route setup in ASP.NET MVC, so I can capture /this-page, /that-page etc.

When you hit a page the action is invoked, say Index(string page) and then page is tested against a value in the database to determine if the page can be found. If it can't be found, I want to display the view FileNotFound which is in my ErrorController, I do not want to redirect as I want to keep the url as http://.../page-that-isnt-found, exactly like StackOverflow does in fact if you give it a bogus question - (http://stackoverflow.com/questions/zzz-aaa).

Now my problem lies with figuring out the code, I have tried both:

[ do page db check ]
if (page == null)
   return RedirectToAction("FileNotFound", "Error");
   // return View("FileNotFound"); // can't opt for a controller ?

The closest I get is with RedirectToAction(), however of course it does an actual redirect, and my url is pointed at /error which is not desired behaviour. I have tried using return View() but it seems I can't specify a controller, only the view name?

+1  A: 

Correct, by returning a View, you are pointing to a View name to be rendered, not an ActionMethod. You should be able to create a View (either in the same controller's views or the shared views) that you return that contains your 404 page content.

Hope this helps.

jchapa
Oh! A shared view! good idea. Would that be the best approach, if I do not want it in the same controller as I would like this 'file not found' screen to be potentially accessible from other controllers? I suppose I could put this in a base controller. Luckily I do not need an associative action method with it, I am happy with just the aspx only rendering for now.
GONeale
Yes, a shared view is what I would recommend for a standard 404/error page. You can access it from any controller. It would be the cleanest option.
jchapa
Thank you jchapa.
GONeale
+1  A: 

You can also use Server.Transfer to preserve the original url. There is good thread on how to make this in asp.net mvc here - http://stackoverflow.com/questions/799511/how-to-simulate-server-transfer-in-asp-net-mvc

Branislav Abadjimarinov