Asp.net mvc 在返回PartialViewResult的方法中返回BadRequest

Asp.net mvc 在返回PartialViewResult的方法中返回BadRequest,asp.net-mvc,model-view-controller,error-handling,viewmodel,partial-views,Asp.net Mvc,Model View Controller,Error Handling,Viewmodel,Partial Views,我有一个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 "

我有一个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);
    }
[HttpGet]公共PartialViewResult GetMyData(int?id)
{
如果(id==null | | id==0)
{
//我想在这里返回一个无效代码,但它必须是“PartialViewResult”类型
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);//未编译
}
var response=MyService.GetMyData(id.Value);
var viewModel=Mapper.Map(response.Value);
返回PartialView(“~/Views/Data/_MyData.cshtml”,viewModel);
}

对于返回PartialViewResult作为其输出的方法,报告错误的正确方法是什么?

您可以创建一个友好的partial error并执行以下操作:

[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);
}
[HttpGet]
公共PartialViewResult GetMyData(int?id)
{
如果(id==null | | id==0)
{
//我想在这里返回一个无效代码,但它必须是“PartialViewResult”类型
返回PartialView(“友好错误”);
}
var response=MyService.GetMyData(id.Value);
var viewModel=Mapper.Map(response.Value);
返回PartialView(“~/Views/Data/_MyData.cshtml”,viewModel);
}

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

老实说,我希望返回值,这样我的前端将显示一条与应用程序中其他所有内容一致的错误消息。如果你需要在视图上显示任何特定的内容,你可以使用
ViewBag
。以上是我将如何实现这一点。