简体   繁体   中英

How to deal with null data in controller/view model

When returning data form a service into the action of a controller, what is the best way to deal with null data. In the example below, I query the service for a Page. But if the page for that Id does not exist, how should I deal with that?

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

Should I create a more elaborate ViewModel that has a boolean property called Found , so I can do something like this:

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

    return View(viewModel);
}

Then in the view model

@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>

What do other people do in this situation? The above situation would work fine, but is there a smarter, or more well regarded way to do this?

Cheers

2 possibilities come to mind:

  1. Display a 404 page:

     public ActionResult Edit(int id) { var page = Services.PageService.GetPage(id); if(page == null) { return HttpNotFound(); } return View(page); } 
  2. If you wanted to display the error on the same view you could include a property on your view model indicating that the item was not found and test against this property in the corresponding view.

So basically it will depend on how you want the error to be presented to the user in this case.

return Content if page is null. like :

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

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

    return View(page);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM