代码之家  ›  专栏  ›  技术社区  ›  David Neale

ASP.NET MVC空视图结果

  •  0
  • David Neale  · 技术社区  · 14 年前

    如何处理返回空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 回复  |  直到 14 年前
        1
  •  2
  •   Jan Willem B    14 年前

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

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

    ErrorView.aspx:

    <div>Person was not found. Try again.</div>
    
        2
  •  1
  •   James H    14 年前

    在这个场景中,我将在人员为空时返回另一个视图,以清晰地分隔视图逻辑:

    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");
    } 
    
        3
  •  0
  •   takepara    14 年前

    我想。。。

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

    并设置自定义错误。