[英]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?
但是,如果该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);
}
Should I create a more elaborate ViewModel that has a boolean property called Found
, so I can do something like this: 如果我应该创建一个更精致的ViewModel,它具有一个名为
Found
的布尔属性,那么我可以执行以下操作:
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: 我想到了两种可能性:
Display a 404 page: 显示404页面:
public ActionResult Edit(int id) { var page = Services.PageService.GetPage(id); if(page == null) { return HttpNotFound(); } return View(page); }
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. 如果page为null,则返回Content。 like :
喜欢 :
public ActionResult Edit(int id)
{
var page = Services.PageService.GetPage(id);
if(page == null)
{
return Content("CANNOT FIND PAGE");
}
return View(page);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.