Friday, February 19, 2010

MVC AJAX Helper

I needed to pass in some arguments to the Create function for the other AJAX extensions and came up with this override.

Thanks to Stephen for the initial help with this article.
http://stephenwalther.com/blog/archive/2008/08/23/asp-net-mvc-tip-36-create-a-popup-calendar-helper.aspx
public static string Create(this AjaxHelper helper, string clientType, string elementId, Dictionary args)
        {
            StringBuilder argSb = new StringBuilder();
            if (args != null && args.Count > 0)
            {
                argSb.Append("{");
                foreach (string key in args.Keys)
                {
                    if (argSb.Length > 1)
                        argSb.Append(",");

                    argSb.Append("'")
                         .Append(key);
                    if (args[key].Contains("$"))
                    {
                        argSb.Append("':")
                             .Append(args[key]);
                    }
                    else
                    {
                        argSb.Append("':'")
                             .Append(args[key])
                             .Append("'");
                    }
                }
                argSb.Append("}");
            }
            //{'class':'element_wrapper'}
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");
            return sb.ToString();
        }

            //{'class':'element_wrapper'}
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");
            return sb.ToString();
        }

3 comments:

Azymn said...

return argSb.ToString(); ?

Seems like a solid approach. Have you tried creating a hashtable of the values and JSONifying it?

Kris Kilton said...

Almost could use this...

JavaScriptSerializer serializer = new JavaScriptSerializer();
string serializedArgs = serializer.Serialize(args);


except the new addition of allowing $get() as the value does not sit well since the values get wrapped in quotes and coded as shown below.

$create(AjaxControlToolkit.CalendarBehavior,{"button":"$get(\u0027img1\u0027)"},null,null,$get('dateField'))});

Kris Kilton said...

Oops, copy and paste dropped my last block of code, updated...