【问题标题】:Returning BadRequest in method that returns PartialViewResult在返回 PartialViewResult 的方法中返回 BadRequest
【发布时间】:2015-10-10 20:23:56
【问题描述】:

我有一个 MVC5 应用程序,它有一个方法填充并返回一个局部视图。由于该方法接受 ID 作为参数,因此如果未提供 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 作为其输出的方法,报告错误的正确方法是什么?

【问题讨论】:

    标签: asp.net-mvc model-view-controller error-handling viewmodel partial-views


    【解决方案1】:

    您可以创建一个友好的错误部分并执行以下操作:

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

    这样可以提供更好的用户体验,而不仅仅是扔给他们任何东西。您可以自定义该错误部分以包含他们做错的一些细节等。

    【讨论】:

    • 老实说,我希望返回值,这样我的前端会显示一条与应用程序中其他所有内容一致的错误消息。但这在紧要关头也能奏效。
    • 如果您需要在视图上显示任何特定内容,您可以随时使用ViewBag 来完成。以上是我将如何实现这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多