2012-02-15 80 views
0

將數據從服務返回到控制器的操作時,處理空數據的最佳方法是什麼?在下面的例子中,我查詢服務的頁面。但是,如果該ID的頁面不存在,我該如何處理?如何處理控制器/視圖模型中的空數據

public ActionResult Edit(int id) 
{ 
    var page = Services.PageService.GetPage(id); 

    if(page == null) 
    { 
     // Do something about it so that the view model doesn't throw an 
     //exception when it gets passed a null Page object 
    } 

    return View(page); 
} 

我應該創建一個具有名爲Found布爾屬性更詳盡的視圖模型,所以我可以做這樣的事情:在視圖模型

public ActionResult Edit(int id) 
{ 
    var page = Services.PageService.GetPage(id); 
    var viewModel = new PageEditViewModel() 
         { 
          Found = (page != null), 
          Page = page 
         }; 

    return View(viewModel); 
} 

然後

@model Payntbrush.Presentation.Demo.MVC3.Areas.Admin.Models.PageIndexViewModel 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Pages</h2> 

<table> 
<tr> 
    <td><strong>Title</strong></td> 

</tr> 

@if (@Model.Found) 
{ 
@foreach (var page in @Model.Pages) 
{ 
    <tr> 
     <td>@page.Title</td> 
     <td>@Html.ActionLink("Edit", "Edit", "Page", new {id = @page.Id})</td> 
    </tr> 
} 
} 
else 
{ 
    <strong>CANNOT FIND PAGE</strong> 
} 
</table> 

什麼其他人在這種情況下做什麼?上述情況可以正常工作,但是有沒有更聰明或者更好的方法來做到這一點?

乾杯

+1

在我看來,它完全取決於你想要做什麼*當發生錯誤。如果在這種情況下顯示「無法找到頁面」就是您想要做的事情,那麼我認爲您的方法沒有任何問題。除此之外,我個人會傳遞null,並在視圖中檢查null。 – 2012-02-15 04:10:14

回答

0

返回頁面爲空的內容。像:

public ActionResult Edit(int id) 
{ 
    var page = Services.PageService.GetPage(id); 

    if(page == null) 
    { 
     return Content("CANNOT FIND PAGE"); 
    } 

    return View(page); 
} 
0

2的可能性浮現在腦海中:

  1. 顯示404頁:

    public ActionResult Edit(int id) 
    { 
        var page = Services.PageService.GetPage(id); 
    
        if(page == null) 
        { 
         return HttpNotFound(); 
        } 
    
        return View(page); 
    } 
    
  2. 如果你想在同一個視圖中顯示的錯誤,您可以包括您的視圖模型中的屬性指示該項目未找到,並在相應視圖中針對此屬性進行測試。

所以基本上,這取決於您希望在這種情況下向用戶呈現錯誤的方式。

相關問題