Aleksa
Aleksa

Reputation: 3114

Call Json function in controller extension method

I am writing Controller extension method which is returning JsonResult. Something like this:

public static class ControllerExtensions
{
    public static JsonResult AjaxRedirect(this Controller cntrl, string action, object routeValues)
    {

    }
}

Is there a way to use protected internal JsonResult Json(object data); function inside this extension method? That function can be used inside any controller method, but I don't know how to use it inside this extension method... And if not, what is the best replacement for it?

Upvotes: 1

Views: 743

Answers (1)

MistyK
MistyK

Reputation: 6232

Create a BaseController for your Controllers which inherits from Controller then wrap Json function into another public function for example JsonPublic() and then make an extension method for BaseController

   public class BaseController : Controller
    {
        public JsonResult JsonPublic(object data)
        {
            return Json(data);
        }
    }


    public static class ControllerExtensions
    {
        public static JsonResult AjaxRedirect(this BaseController cntrl, string action, object routeValues)
        {
            cntrl.JsonPublic() // accessible
        }
    }

Upvotes: 2

Related Questions