views:

89

answers:

1

I find myself needing to return various JSON results to the client from my controller actions. I have created static "helper" methods of the type ContentResult. I want to be able to reuse these helpers in multiple projects, so I've created them in their own class, and someday soon I'll move them to their own assembly.

Here is my question: Some of these return helpers need access to the controller context, so I've create then as extension methods on Controller. I like the way Html Helper methods are extension methods on the HtmlHelper class, but I can't find a suitable controller property similar the the Html property on the View class, so I just extended controller. Below is the code from on return helper. I want to know if there is a better way to do this.

    public static ContentResult AJAXRedirect(this Controller cont, string action,
        string controller, object routeValues)
    {
        string url = cont.Url.Action(action, controller, routeValues);
        string json = "{{\"redirect\": \"{0}\" }}";
        json = string.Format(json, url);
        return new ContentResult
        {
            Content = json,
            ContentType = "text/x-json",
            ContentEncoding = Encoding.UTF8
        };
    }
+2  A: 

You can use this code:

string url = cont.Url.Action(action, controller, routeValues);
return Json(new { redirect : url });

Extending Controller seems to be good way. Content(), View(), Json(), Empty() methods are also Controller extensions. You are adding your own.

EDIT

Sorry, I was actually wrong about extension methods. They are not extension methods. So it would be better if you used your own base Controller class with additional methods. Since you'll be using these methods inside of your classes, inheritance is the best solution. you can still share this class between projects.

LukLed
If they are extensions on controller and mine is too, then why do I have to invoke mine like: this.AJAXRedirect() but I don't have to use this with the others?
Josh Pearce
@LukLed, I do have a base controller class, however a lot of project specific stuff ends up getting into it, so it's not practical to share it between projects. I though I read somewhere about a formal way to have Result Helpers, but I can't find it now.
Josh Pearce
@Josh Pearce: You don't have to use one base controller class. You can create one for every project, inherit from it, and have another, independent, for specific project.
LukLed