在 returns PartialViewResult 的方法中返回 BadRequest

Returning BadRequest in method that returns PartialViewResult

我有一个 MVC5 应用程序,它有一个方法 populates 和 returns 一个局部视图。由于该方法接受 ID 作为参数,如果未提供,我想 return 报错。

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

对于 return 将 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);
}

这样可以获得更好的用户体验,而不是随便扔给他们任何东西。您可以自定义该错误部分以包含他们做错的一些详细信息等。

您可以使用手动 Exception

 if (id == null || id == 0)
 {
    throw new Exception("id must have value");
 }

如果您使用 ajax,您可以通过 error callback function

处理错误
    $.ajax({
         type: 'POST',
         url: '/yourUrl',
         success: function (response) {
             // call here when successfully // 200
         },
          error: function (e) {
            // handle error in here 
        }
    })