David Neale
David Neale

Reputation: 17018

ASP.NET MVC null ViewResult

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?

Upvotes: 0

Views: 790

Answers (3)

takepara
takepara

Reputation: 10433

I think...

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

and set custom errors.

Upvotes: 0

James H
James H

Reputation: 2401

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");
} 

Upvotes: 1

Jan Willem B
Jan Willem B

Reputation: 3806

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>

Upvotes: 2

Related Questions