我有一个MVC5应用程序,它有一个方法填充并返回一个局部视图。由于该方法接受ID作为参数,因此Id喜欢在未提供错误时返回错误。
[HttpGet] public PartialViewResult GetMyData(int? id)
{
if (id == null || id == 0)
{
// I'd like to return an invalid code here, but this must be of type "PartialViewResult"
return new HttpStatusCodeResult(HttpStatusCode.BadRequest); // Does not compile
}
var response = MyService.GetMyData(id.Value);
var viewModel = Mapper.Map<MyData, MyDataViewModel>(response.Value);
return PartialView("~/Views/Data/_MyData.cshtml", viewModel);
}
为返回PartialViewResult作为输出的方法报告错误的正确方法是什么?
答案 0 :(得分:2)
您可以创建友好的错误部分并执行以下操作:
[HttpGet]
public PartialViewResult GetMyData(int? id)
{
if (id == null || id == 0)
{
// I'd like to return an invalid code here, but this must be of type "PartialViewResult"
return PartialView("_FriendlyError");
}
var response = MyService.GetMyData(id.Value);
var viewModel = Mapper.Map<MyData, MyDataViewModel>(response.Value);
return PartialView("~/Views/Data/_MyData.cshtml", viewModel);
}
这样可以提供更好的用户体验,而不仅仅是扔掉任何东西。您可以自定义该错误部分以包含他们做错的一些细节等。