ASP.NET MVC null ViewResult

时间:2010-05-11 08:48:33

标签: asp.net asp.net-mvc

如何处理返回null ViewResult的MVC控制器?

作为一个例子,我正在创建一个简单的编辑视图:

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

我想实际上在控制器中检查空结果是没有意义的,因为视图从模型中挑选出属性:

<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>
<% } %>

我可以把所有东西都包裹在<% if(Model != null) { //render edit markup...等等,但这似乎相当不优雅。有没有更好的方法来解决这个问题?

3 个答案:

答案 0 :(得分:2)

在这种情况下,如果person变为空,则似乎是错误的。如果是这种情况,您可以呈现不同的(错误)视图。例如:

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

return View(person);

ErrorView.aspx:

<div>Person was not found. Try again.</div>

答案 1 :(得分:1)

在这种情况下,当person为null时,我会返回另一个视图,以便干净地分离您的视图逻辑:

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

答案 2 :(得分:0)

我想......

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

并设置自定义错误。