我有一个 MVC5 应用程序,它有一个填充并返回部分 View 的方法。由于该方法接受 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 作为其输出的方法报告错误的正确方法是什么?
最佳答案
您可以创建一个友好的错误部分并执行以下操作:
[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);
}
这样可以提供更好的用户体验,而不是只是向他们扔任何东西。您可以自定义该错误部分以包含他们做错的一些详细信息等。
关于asp.net-mvc - 在返回 PartialViewResult 的方法中返回 HttpStatusCodeResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538084/