4

How can I do this in another way ?

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = GetMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var notFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("~/Views/Shared/NotFound.cshtml", notFoundViewModel);
    }
}

Exception will be thrown for url Controller/SomeAction/NotFoundId. I hate to have in project something like: ~/Views/Shared/NotFound.cshtml.

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54

3 Answers3

5

I realize this question is a few years old, but I figured I would add to the accepted answer. Following CodeCaster's recommendation of using the standard "Error.cshtml" as the file (view) to act as your generic error page, I recommend you let the MVC framework do the rest of the work for you.

If you place the Error.cshtml file in the Shared folder in your MVC project, you do not need to explicitly specify the path to the view. You can rewrite your code like the following:

public ActionResult SomeAction(int id)
{
    try
    {            
        var model = getMyModel(id);
        return View(model);
    }
    catch(Exception e)
    {
        var NotFoundViewModel = new NotFoundViewModel { Some Properties };
        return View("Error", NotFoundViewModel);
    }
}

In fact, I've noticed that if you supply an explicit path and are running the Visual Studio IIS Express on your local machine, it sometimes isn't able to find the file and displays the generic 404 message :(

Savantes
  • 103
  • 1
  • 7
2

You can return HttpNotFoundResult object as:

catch(Exception e)
{
    return new HttpNotFoundResult();
}

or

catch(Exception e)
{
    return HttpNotFound("ooops, there is no page like this :/");
}
Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
1

Make it a "~/Views/Shared/Error.cshtml" that displays a generic error model with a title and a message?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    This looks good . I must have an error controller so i can return RedirectToAction with NotFoundAction and my NotFoundViewModel as params . And in NotFoundAction i'll render my NotFoundView . Is that ok ? – Razvan Dumitru Aug 07 '13 at 10:43
  • 1
    Or take a look at [this question](http://stackoverflow.com/questions/11851328/how-is-error-cshtml-called-in-asp-net-mvc). – CodeCaster Aug 07 '13 at 10:58