0

How should one deal with an MVC controller returning a null ViewResult?

As an example I am creating a simple edit view:

    public ActionResult Edit(int id)
    {
        var person = (from p in context.SWLiftShare_Persons
                      where p.id == id
                      select p).SingleOrDefault();

        if (person != null)
        {
            return View(person);
        }
        else return View();
    }

I guess in reality there's no point in checking for a null result in the controller because the view picks out properties from the model:

<h2>Edit - <%= Html.Encode(Model.Name) %></h2>

<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="id">id:
            <%= Html.Encode(Model.id) %></label>
        </p>
        <p>
            <label for="CollarNumber">CollarNumber:</label>
            <%= Html.TextBox("CollarNumber", Model.CollarNumber)%>
            <%= Html.ValidationMessage("CollarNumber", "*") %>
        </p>
        <p>
            <label for="Name">Name:</label>
            <%= Html.TextBox("Name", Model.Name)%>
            <%= Html.ValidationMessage("Name", "*") %>
        </p>
        <p>
            <label for="EmailAddress">EmailAddress:</label>
            <%= Html.TextBox("EmailAddress", Model.EmailAddress, new { style = "width:300px" })%>
            <%= Html.ValidationMessage("EmailAddress", "*") %>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

I could just wrap everything in a <% if(Model != null) { //render edit markup... etc. but that seems rather unelegant. Is there a better way to deal with this?

3 Answers 3

2

In this case it seems to be an error if person becomes null. You could render a different (error) view if this is the case. For example:

if (person == null) 
{
  return View("ErrorView");
}

return View(person);

ErrorView.aspx:

<div>Person was not found. Try again.</div>
Sign up to request clarification or add additional context in comments.

Comments

1

In this scenario, I would return another view when the person is null to cleanly separate your view logic:

public ActionResult Edit(int id)  
{  
    var person = (from p in context.SWLiftShare_Persons  
                  where p.id == id  
                  select p).SingleOrDefault();  

    return (person != null) ? View(person) : View("InvalidPerson");
} 

Comments

0

I think...

throw new HttpException(404,"Not found");

and set custom errors.

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.