views:

430

answers:

1

hello.

I need some advice for the best approach to use in developing embeddable widgets that my site users could use to show our content on their site.

Let's say we have some content which uses a jquery plugin to be rendered, and we want to give our customers an easy way to embed it in their websites.

one option could be of using an IFrame, but as we know this is quite invasive and has some problems. I'd like to know your opinion on that, too.

another approach could be giving a code like this, to show item #23:

<DIV id="mysitewidget23"><script src="http://mysite.com/scripts/wdg.js?id=23" /></DIV>

and somehow (help needed here...) creating server-side the wdg.js script to inject content, jquery, needed plugins, inside the DIV.

this looks more promising, since the user can customize to a certain extent the style of the DIV, and no IFRAME is needed. But how which is the best and more efficient way to do this in ASP.NET MVC?

There are of course many other approaches to achieve what we need, and I'd really appreciate any idea you can give.

thanks in advance

+3  A: 

JSONP is one way to do this. You start by writing a custom ActionResult that will return JSONP instead of JSON which will allow you to work around the cross-domain ajax limitation:

public class JsonpResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;

        if (!string.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }

        if (Data != null)
        {
            var request = context.HttpContext.Request;
            var serializer = new JavaScriptSerializer();
            if (null != request.Params["jsoncallback"])
            {
                response.Write(string.Format("{0}({1})", 
                    request.Params["jsoncallback"], 
                    serializer.Serialize(Data)));
            }
            else
            {
                response.Write(serializer.Serialize(Data));
            }
        }
    }
}

Then you could write a controller action that returns JSONP:

public ActionResult SomeAction()
{
    return new JsonpResult
    {
        Data = new { Widget = "some partial html for the widget" }
    };
}

And finally people can call this action on their sites using jquery:

$.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?', 
    function(json)
    {
        $('#someContainer').html(json.Widget);
    }
);

If users don't want to include jQuery on their site you might write a javascript on your site that will include jQuery and perform the previous getJSON call, so that people will only need to include a single js from site as in your example.


UPDATE:

As asked in the comments section here's an example illustrating how to load jQuery dynamically from your script. Just put the following into your js:

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (!jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"&gt;&lt;/scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
        $(function() {  
            $.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?', 
                function(json) {
                    // Of course someContainer might not exist 
                    // so you should create it before trying to set
                    // its content
                    $('#someContainer').html(json.Widget);
                }
            );
        });
    }
}
initJQuery();   
Darin Dimitrov
This seems a very clever solution, thanks Darin.I've implemented it, and it works well if I explicitly include jquery and the needed plugins in the "customer" page. As you have guessed in your last paragraph I'd like to try to include a single <script> tag to my server, and include jquery in this but I cannot understand how to achieve that.I cannot add <script> explicitly inside my generated script file, so I have tried to inject it with document.write, or eval, but with no luck. The jquery script file is not interpreted, and the following code fails with $ is undefined error.any idea?tnx
marco
Please see my update.
Darin Dimitrov
Thanks, it looks promising! I'll try it tomorrow and let you know!
marco
works like a charm.
marco
Hi Guys - this looks like a great solution but I'm a little bit unsure of something: can you please explain what this line means? `Data = new { Widget = "some partial html for the widget" }` ? Is `Widget` some kind of custom class? Is it a PartialView? In the ActionMethod, how does JsonpResult know what `Data` type is? Where's it defined? Thanks
DaveDev