0

I have a controller that passes data to a view:

 public ViewResult Details(int id)

In the case that id is invalid i would like to return an empty or error view and not passing data to the Details view that is strongly typed and waits data that cannot arrive.

How can i handle generic error views?

4 Answers 4

1

We have an Error action on our base controllers which the real controllers inherit from. If the input fails validation, redirect to the Error action passing some error message text that will be shown in the view. This allows you to have a standard error view across all controller actions.

Sign up to request clarification or add additional context in comments.

Comments

1

You could redirect to any view you would like:

return View("Error", "This is a error message");

The code above will redirect to the Error.cshtml view and pass a string with a message.

Comments

1

Just return your error view as required:

if( // id is invalid)
{
 return View("MyErrorView");
}

Comments

1

If ID is invalid, do not return empty content, that is in fact typical story for HTTP status 404 - not found - in MVC, you can handle it easy, like this :

if (IdIsInvalid(id))
return HttpNotFound();

As an alternative, you can call

throw new HttpException(404, "NotFound");

and handle your 404 errors globally, for example with setting in your web.config :

<configuration>
<system.web>
    <customErrors mode="On">
      <error statusCode="404" redirect="~/NotFound"/>
    </customErrors>
</system.web>

1 Comment

The problem with handling the error globally through the web.config is that the client ends up getting a 302 (redirect) rather than the desired 404 (not found.) But I do agree that using the proper HTTP code is a good approach.

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.