Search code examples
asp.net-mvcmodel-view-controllererror-handlingviewmodelpartial-views

Returning HttpStatusCodeResult in method that returns PartialViewResult


I have an MVC5 application that has a method populates and returns a partial view. Since the method accepts an ID as a parameter, Id like to return an error if it is not supplied.

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

What is the proper way to report an error for a method that returns a PartialViewResult as its output?


Solution

  • You could create a friendly error partial and do the following:

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

    This way there is a better user experience rather than just throwing them anything. You can customise that error partial to include some details that they did wrong etc.