Building A Color Picker Using ASP.NET MVC And jQuery - Update
I like how people are coming up with alternatives for the Ajax Toolkit but one thing I will say in this case is MVC is intended to separate data from the output. It's a huge no no in my mind to add HTML to your controller. The controller returns a JsonResult which means it should be purely Json and not include HTML. Your script should build and render the HTML client-side.
I did blur what really should be returned from an action. I thought I would update the article so that my action only return a JsonResult and not the HTML table.
I've updated the controller to return a list of colors in a generic string collection:
C#
public class ColorController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult FetchColors()
{
var colors = new List<Color>();
foreach (var color in Enum.GetNames(typeof(KnownColor)))
{
var colorValue = ColorTranslator.FromHtml(color);
var html = string.Format("#{0:X2}{1:X2}{2:X2}",
colorValue.R, colorValue.G, colorValue.B);
colors.Add(new Color { Html = html});
}
return Json(colors.ToArray());
}
}
public class Color
{
public string Html { get; set; }
}
VB.NET (Converted)
Public Class ColorController
Inherits Controller
<AcceptVerbs(HttpVerbs.Get)> _
Public Function FetchColors() As JsonResult
Dim colors = New List(Of Color)()
For Each color In System.Enum.GetNames(GetType(KnownColor))
Dim colorValue = ColorTranslator.FromHtml(color)
Dim html = String.Format("#{0:X2}{1:X2}{2:X2}", colorValue.R, colorValue.G, colorValue.B)
colors.Add(New Color With {.Html = html})
Next color
Return Json(colors.ToArray())
End Function
End Class
Public Class Color
Private privateHtml As String
Public Property Html() As String
Get
Return privateHtml
End Get
Set(ByVal value As String)
privateHtml = value
End Set
End Property
End Class
Now the action is return purely what the return type is and that is JSON. This means the rendering of the table is in the hands of the front end. Thankfully there's a jQuery library called jTemplates. Quite simply jTemplates is a template engine for jQuery. You create a template and pass it data, and it renders it for you. Sweet!
Here's the updated View:
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4a2.js"></script>
<script language="javascript" type="text/javascript" src="http://jtemplates.tpython.com/jTemplates/jquery-jtemplates.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#Colors").hide();
$("#SelectColor").click(function() {
$.getJSON("/Color/FetchColors", null, function(data) {
$("#Colors").setTemplateURL("Templates/ColorPicker.htm");
$("#Colors").processTemplate(data);
$("#Colors").show();
});
});
$("td").live("mouseover", (function() {
$("#Sample").css("background-color", $(this).css("background-color"));
$(this).css("cursor", "pointer");
}));
$("td").live("click", function() {
$("#SelectedColor").val($(this).attr("bgcolor"));
});
});
</script>
<input type="text" id="SelectedColor" name="SelectedColor" readonly="readonly" />
<img src="/Content/Images/cp_button.png" alt="Pick a color" align="absmiddle" id="SelectColor" />
<span id="Sample"> </span><br /><br />
<div id="Colors"></div>
I've modified the code above to use jQuery's $.getJSON function:
$.getJSON("/Color/FetchColors", null, function(data) {
When data it returned from the server, I pass a template to jTemplates:
$("#Colors").setTemplateURL("Templates/ColorPicker.htm");
Then I run processTemplate, which basically means render the template now:
$("#Colors").processTemplate(data);
And finally here's the template file:
<table>
<tbody>
<tr>
{#foreach $T as color}
<td bgcolor="{$T.color.Html}"> </td>
{#/for}
</tr>
</tbody>
</table>
Nice and simple. Now the action returns only JSON and the front end renders the HTML. This is a much better way to implement this code. Thanks to you the readers for pointing out pieces that we miss. It makes us all better programmers. The entire source code of this article can be downloaded over here
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @
malcolmsheridan