<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nathan Bridgewater &#187; jQuery</title>
	<atom:link href="http://www.integratedwebsystems.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Fri, 10 Sep 2010 16:13:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Cross-domain JsonP using Asp.net MVC and jQuery</title>
		<link>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/</link>
		<comments>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 05:27:01 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=897</guid>
		<description><![CDATA[So there are a couple great walkthroughs out there that talk about using jquery jsonp in cross-domain scenarios.&#160; They talk a lot about the requesting and server side, but not so much about how to use the callback. So to clarify, I’ll step through what I did to make this work including providing my implementation [...]]]></description>
			<content:encoded><![CDATA[<p>So there are a couple <a href="http://abcoder.com/javascript/jquery/jsonp-first-timer/">great walkthroughs</a> out there that talk about using <a href="http://api.jquery.com/jQuery.ajax/">jquery jsonp</a> in cross-domain scenarios.&#160; They talk a lot about the requesting and server side, but not so much about how to use the callback. So to clarify, I’ll step through what I did to make this work including providing my implementation for a new ActionResult called JsonPResult for <a href="http://www.asp.net/mvc">MVC</a>.</p>
</p>
<p> <span id="more-897"></span>
</p>
<p>Starting out, client-side on the calling page, I setup my script. This function makes a request to the server and expects a jsonp response back. The default “success” handler is optional here and will be invoked along-side the one you specify for jsonp.</p>
<pre class="brush: js; gutter: false;">$.ajax({
    url: 'http://other-domain/api/GetInformation',
    data: { key: 'some data key, this parameter is optional' },
    type: &quot;GET&quot;,
    dataType: &quot;jsonp&quot;,
    jsonpCallback: &quot;localJsonpCallback&quot;
});

function localJsonpCallback(json) {
    //do stuff...
}</pre>
<p>We need to setup the server side.&#160; I’m using Asp.Net MVC, so I built this new ActionResult for handling Jsonp GET requests. I copied most of the code from the original JsonResult class in System.Web.MVC Ms-Pl code. Before I show you that, you should see it in action. Here I have a controller action that uses JsonpResult:</p>
<pre class="brush: js; gutter: false;">public JsonpResult GetInformation(string key)
{
    var resp = new Core.Model.CustomObject();
    if (validateKey(key))
    {
        resp.Data = &quot;some custom message&quot;;
        resp.Success = true;
    }
    else
        resp.Message = &quot;unauthorized&quot;;

    return this.Jsonp(resp); //using extension method
}</pre>
<p>This automatically handles all the fancy Jsonp work that goes on behind the scenes.&#160; It serializes the custom object into Json and wraps it with the callback function. So your response appears something like this:</p>
<pre class="brush: js; gutter: false;">localJsonpCallback({&quot;Data&quot;:{&quot;Success&quot;:true, Message: &quot;some custom message&quot;}});</pre>
<p>I setup an extension method to use<em> controller.Jsonp(object)</em> just as you do the existing <em>controller.Json(object)</em> method already available. This should make it a lot easier to handle. It will inspect the call for the json callback itself so you also don’t have to manually pull it from the request.&#160; It will also work with the two different types of callback requests parameters in use out there like: “jsoncallback” and “callback.”</p>
<pre class="brush: csharp; gutter: false;">/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 *
 * Content of this class was mostly derived from the original
 * JsonResult class in the System.Web.Mvc 2.0 RTM Assembly. This
 * has beeen slightly extended for use with JSONP calls.
 *
 * This software is subject to the Microsoft Public License (Ms-PL).
 * A copy of the license can be found in the license.htm file included
 * in this distribution.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

namespace System.Web.Mvc
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.Mvc.Resources;
    using System.Web.Script.Serialization;

    public class JsonpResult : ActionResult
    {

        public JsonpResult()
        {
        }

        public Encoding ContentEncoding
        {
            get;
            set;
        }

        public string ContentType
        {
            get;
            set;
        }

        public object Data
        {
            get;
            set;
        }

        public string JsonCallback { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(&quot;context&quot;);
            }

            this.JsonCallback = context.HttpContext.Request[&quot;jsoncallback&quot;];

            if (string.IsNullOrEmpty(this.JsonCallback))
                this.JsonCallback = context.HttpContext.Request[&quot;callback&quot;];

            if (string.IsNullOrEmpty(this.JsonCallback))
                throw new ArgumentNullException(&quot;JsonCallback required for JSONP response.&quot;);

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = &quot;application/json&quot;;
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                response.Write(string.Format(&quot;{0}({1});&quot;, this.JsonCallback, serializer.Serialize(Data)));
            }
        }
    }

    //extension methods for the controller to allow jsonp.
    public static class ContollerExtensions
    {
        public static JsonpResult Jsonp(this Controller controller, object data)
        {
            JsonpResult result = new JsonpResult();
            result.Data = data;
            result.ExecuteResult(controller.ControllerContext);
            return result;
        }
    }
}</pre>
<p>When the response is downloaded from the client, it’s invoked and you handle it just as you normally would with any other getJSON success handler. So hopefully this helps clear up any confusion with using JsonP.&#160; There’s about a thousand suggestions I found on doing cross domain JSON and this was just one of the many. I also wrote a simple JsonWebClient class in .Net that will permit the server-side proxy POST to another domain if anyone is interested. I did that before I learned about CORS (preflight post) or this, JsonP. Comments are welcome!</p>
<h3>Sample Code</h3>
<p>Additionally, here is a simple, working demo showing how this works. Be sure to start both websites. Then browse the ClientWebsite and click Test JSONP. This will perform a JSONP GET to the second website.</p>
<p><a href="/resources/p897/JsonPDemo.zip">Download the sample</a></p>
<p>This project is also in the <a href="http://github.com/nathanb/iws-snippets">IWS Snippets project</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using jQuery Modal Dialog Confirmation with an ASP.NET Server Control</title>
		<link>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/</link>
		<comments>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 22:07:07 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[dialog]]></category>
		<category><![CDATA[modal]]></category>
		<category><![CDATA[postback]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=413</guid>
		<description><![CDATA[So the other day, I wanted to build a confirmation dialog using jQuery with an existing Asp.Net web forms Button control.  I wanted this dialog to be modal; and upon confirmation, I wanted it to postback using the Button&#8217;s server-side click event.  After toying with the jQuery dialog, I realized that its dialog doesn’t suspend [...]]]></description>
			<content:encoded><![CDATA[<p>So the other day, I wanted to build a confirmation dialog using jQuery with an existing Asp.Net web forms Button control.  I wanted this dialog to be modal; and upon confirmation, I wanted it to postback using the Button&#8217;s server-side click event.  After toying with the jQuery dialog, I realized that its dialog doesn’t suspend the process while waiting for user input. So it also causes problems with confirmation since clicking the original button will always postback. So with a few tweaks, you can prevent the postback and emulate the click event pretty easily.</p>
<p><span id="more-413"></span></p>
<h3>Setup the Dialog and Postback Script</h3>
<p>In my application, we may click the button multiple times. So you’ll need to initialize it on load and actually open it later. As you can see below, we&#8217;re making our dialog modal and setting its autoOpen to false to prevent it from opening during initialization.  The dialog contains two buttons, and in this initialization, we can define their handler code. The confirmation button “Yes, I Understand and Agree” runs a chunk of code emulates the server control Click event on Button1. Notice I used the inline server-side script to gain access to the Page.ClientScript object, which contains a nice handful of helper functions for javascript.</p>
<pre class="brush: js; gutter: false; toolbar: false;">$().ready(function() {
    $("#ConfirmPanel").dialog(
    { autoOpen: false,
        modal: true,
        bgiframe: true,
        width: 400,
        height: 300,
        buttons: {
            'Youbetcha': function() {
                &lt;%=this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this.Button1))%&gt;;
            },
            'No Thanks': function() {
                $(this).dialog('close');
            }
        }
    })
});</pre>
<h3>Open the Dialog with OnClientClick</h3>
<p>Next we’ll open the dialog each time our original server control button is clicked. You use the OnClientClick property to do this.</p>
<pre class="brush: js; gutter: false; toolbar: false;">$("#ConfirmPanel").dialog('open'); return false;</pre>
<p>We always return false here. Since the dialog doesn’t suspend the process, it will always finish and immediately postback. So by returning false, we’re preventing the button from posting back and allowing the jquery dialog to appear.</p>
<p>Here’s the full Asp.Net markup:</p>
<pre class="brush: xml; gutter: false; toolbar: false;">&lt;asp:Label ID="lblClicked" runat="server" /&gt;
&lt;asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Test" OnClientClick="javascript: $('#ConfirmPanel').dialog('open'); return false;"/&gt;
&lt;div id="ConfirmPanel" style="width: 400px; height: 200px;"&gt;
    &lt;h2&gt;Terms and Conditions&lt;/h2&gt;
    &lt;p&gt;By accepting, you agree to the following:
        &lt;ul&gt;
            &lt;li&gt;Are you really, really sure???? &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/p&gt;
&lt;/div&gt;</pre>
<h3>The Result</h3>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image_thumb.png" border="0" alt="image" width="534" height="325" /></a></p>
<p>Clicking Youbetcha fires the Click event for our Button1.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image1.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image_thumb1.png" border="0" alt="image" width="126" height="36" /></a></p>
<p>Updated: 2/16/2010</p>
<p>To answer Matt’s question, I setup a simple web forms page with a data grid and a button within its rows. All the buttons are wired to one event handler and their command argument property is used to provide identifying data to the event handler.  Having said that, here’s the same solution using dynamic confirmation dialog. If you click OK, it will postback using the original button’s information which is displayed on postback.  Noticed I placed a <em>ClientScript.GetPostBackEventReference(uxGrid, string.Empty)</em> within the PageLoad event. Every time the page loads, postback or not, I want it to do this so it will render the __doPostBack client-side function. Without that, it will only work the first time. Subsequent clicks after the first postback will break.</p>
<p>So essentially the solution is to use __doPostBack(clientside_input_name_attribute, &#8221;).  Using the javascript function below we rebuild the buttons for the dialog each time and rewire it to the appropriate location.  So for this, if you didn&#8217;t want to use a grid, you could still use it the same way via OnClientClick with &#8220;this.name&#8221; and pass that to __doPostBack.</p>
<p>Here’s the markup source.  You can also <a href="/resources/p413/jquery_dynamic_confirmation.zip">download the full source code here</a>.</p>
<p>Thanks Matt.</p>
<pre class="brush: xml; gutter: false;">&lt;%@ Page Language="C#" AutoEventWireup="true"  %&gt;
&lt;%@ Import Namespace="System.Collections.Generic" %&gt;

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
    &lt;title&gt;&lt;/title&gt;

    &lt;script type="text/C#" runat="server"&gt;
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.GetPostBackEventReference(uxGrid, string.Empty);

            if (!Page.IsPostBack)
            {
                List&lt;int&gt; test = new List&lt;int&gt;();
                test.Add(2);
                test.Add(3);
                test.Add(32);
                test.Add(223);
                test.Add(5);
                test.Add(8);
                uxGrid.DataSource = test;
                uxGrid.DataBind();

            }
        }
        protected void uxRowAction_Click(object sender, EventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                uxTest.Text = "clicked " + b.CommandArgument;
            }
        }

    &lt;/script&gt;

    &lt;link href="smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" /&gt;
    &lt;script src="jquery-1.3.2.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="jquery-ui-1.7.2.custom.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        $().ready(function() {
            $('#dialogContent').dialog({
                autoOpen: false,
                modal: true,
                bgiframe: true,
                title: "MySql Membership Config Tool",
                width: 800,
                height: 600
            });
        });

        function rowAction(uniqueID) {

            $('#dialogContent').dialog('option', 'buttons',
                {
                    "OK": function() { __doPostBack(uniqueID, ''); $(this).dialog("close"); },
                    "Cancel": function() { $(this).dialog("close"); }
                });

                $('#dialogContent').dialog('open');

            return false;
        }

    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div id="dialogContent"&gt;
        &lt;h3&gt;confirm&lt;/h3&gt;
        &lt;p&gt;Click ok to accept&lt;/p&gt;
    &lt;/div&gt;
    &lt;asp:Literal ID="uxTest" runat="server" /&gt;
    &lt;div&gt;
        &lt;asp:DataGrid ID="uxGrid" runat="server" AutoGenerateColumns="false"&gt;
            &lt;Columns&gt;
                &lt;asp:TemplateColumn&gt;
                    &lt;ItemTemplate&gt;
                        &lt;asp:Button ID="uxRowAction" runat="server" CommandArgument='&lt;%#Container.DataItem.ToString() %&gt;' Text="Row Action" OnClick="uxRowAction_Click" OnClientClick="javascript:return rowAction(this.name);" /&gt;
                    &lt;/ItemTemplate&gt;
                &lt;/asp:TemplateColumn&gt;
            &lt;/Columns&gt;
        &lt;/asp:DataGrid&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>
