Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 344
Rethic Avatar asked Apr 14 '26 14:04

Rethic


1 Answers

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.

like image 92
Jamie Rees Avatar answered Apr 16 '26 11:04

Jamie Rees