'Returning BadRequest 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 1:[1]

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.

Solution 2:[2]

You can use manual Exception

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

if you work with ajax, you can handle error by error callback function

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jamie Rees
Solution 2 Zanyar J.Ahmed