Josh Pearce
Josh Pearce

Reputation: 3455

ASP.NET MVC Result Return Helper

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

Upvotes: 0

Views: 1706

Answers (1)

LukLed
LukLed

Reputation: 31862

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.

Upvotes: 2

Related Questions