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
.
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 :(
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 :/");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With