jQuery-ASP.NET MVC : 'JQueryAjaxLink' HtmlHelper

Building on my form helper example from yesterday, I was inspired to build a ‘jquery ajax’ action link.

It looks like the following:

<%= Html.JQueryAjaxLink<HomeController>("testLink", "TestLink", c => c.AjaxTestControl(),
new Hash(beforeSend => "onRequest", success => "onResponse"))%>
The signature for jQueryAjaxLink:
public static string JQueryAjaxLink<TController>(this HtmlHelper helper,
string id, string text, Expression<Action<TController>> linkAction, IDictionary ajaxOptions)
where TController : Controller
        {
return AjaxBuilder.RenderLink(id, text,
helper.BuildUrlFromExpression<TController>(linkAction), ajaxOptions);
}

The IDictionary ‘ajaxOptions’ accepts a key/pair listing of values.

Here is a sample of the normal jQuery ‘ajax’ call:

$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
( http://docs.jquery.com/Ajax/jQuery.ajax#options )

A couple of notes:

1. I don’t use the data, as a matter of fact, I have it currently hardcoded to ‘data:{}’

2. Hand in hand with #1 above, I use RESTful urls to match the ASP.NET MVC Controller/Actions.

So I’m populating the ‘url’ with the helper.BuildUrlFromExpression<TController>(linkAction) – ie. c => c.AjaxTestControl() as seen above.

The ‘AjaxBuilder’ from above creates the link:

public class AjaxBuilder
    {
public static string RenderLink(string controlId, string text,
string action, IDictionary ajaxOptions)
{
StringBuilder js = new StringBuilder();
js.Append("$.ajax({type: 'POST',");
js.AppendFormat("url:'{0}',", action);
foreach (DictionaryEntry entry in ajaxOptions)
{
js.AppendFormat("{0}:{1},", entry.Key, entry.Value);
}
js.Append("data:'{}'"); //use RESTFUL urls
            js.Append("});return false;");
string link = string.Format("<a href=\"#\", name=\"{0}\" id=\"{0}\" onclick=\"{1}\">{2}</a>",
controlId, js.ToString(), text);
return link;
}
}

(I am naming this ‘RenderLink’ as I plan on also creating a dropdown ajax control to go along with this)

Advertisements