Adding a rich text editor to ASP.NET MVC using strongly typed helpers, DataAnnotations & jQuery

by Matt Palmer February 15, 2010
You may have read about the new strongly-typed helpers in ASP.NET MVC 2. In addition to the HTML element helpers like Html.TextBoxFor(), you can use the more generic Html.EditorFor() to build your own template for editing a custom data type. In this post, I'll show you how to create a single template you can use for any forms that need a rich text editor. UIHints using Using DataAnnotations First, we need to specify the type of data we'll be building a template for. We'll use a simplified CMS model as an example: public class CMSPage { public CMSPage() { } string Title { get; set; } string URL { get; set; } string Content { get; set; } } Using DataAnnotations, we can specify the type of each of these elements: public class CMSPage { public CMSPage() { } [DataType(DataType.Text)] string Title { get; set; } [DataType(DataType.Url)] string URL { get; set; } [DataType(DataType.Html)] string Content { get; set; } } We have already provided enough information for the EditorFor to build a decent edit form for our CMSPageobject—but with a UIHint we can make this even better: public class CMSPage { public CMSPage() { } [DataType(DataType.Text)] string Title { get; set; } [DataType(DataType.Url)] string URL { get; set; } [DataType(DataType.Html)] [UIHint("Html")] string Content { get; set; } } EditorFor now knows we want to use the "Html" template for the Content field—now we just need to create the template. Custom EditorTemplates Create a new folder in Views/Shared called EditorTemplates, and create a new partial view, Html.ascx, in that folder. Since this template will be used for editing HTML, we can use string as the type. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %> <%= Html.TextArea("", Model, new { @class = "html" })%> Now the EditorFor helper will use our new Html.ascx template for any fields we've specified to be HTML using the UIHint attribute. Currently our template is just a textarea with the CSS class htmlapplied, but with a little jQuery and progressive enhancement we can improve on that. Upgrading your textarea with markItUp! markItUp! is a jQuery plugin that lets you turn any textarea into a rich text editor for any number of text formats—we'll be looking at an editor for HTML, but there are markItUp! sets available for formats like Textile, markdown, wikis, and many others. After downloading the latest release and the Html set, add the required CSS and JavaScript references: <link rel="stylesheet" type="text/css" href="markitup/skins/markitup/style.css" /> <link rel="stylesheet" type="text/css" href="markitup/sets/html/style.css" /> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="markitup/jquery.markitup.js"></script> <script type="text/javascript" src="markitup/sets/html/set.js"></script> Now all we need to upgrade our textarea to a rich text editor is: jQuery(function ($) { $('textarea.html').markItUp(mySettings); }); So what are the advantages of this approach? Reusable - all you need to do to add the same editor support to another field on any model is to add the appropriate UIHelper attribute. You could even develop several templates like this to use as a standard base project. DRY - there is exactly one place to change the editor for all "Html" type fields. Consistent - you can be sure that all "Html" fields will have the same editor control.

Tags: ,

Sorting/Filtering a generic List using delegates

by Steven Applegate February 3, 2010
This is a nice little technique to easily sort a generic List using delegates. Say you have the following class: publicclassProduct{    privateint _ProductID;    privatestring _Name;    privatedecimal _Price;    public Product(int productid, string name, decimal price)    {        _ProductID = productid;        _Name = name;        _Price = price;    }    publicint ProductID    {        get { return _ProductID; }        set { _ProductID = value; }    }    publicstring Name    {        get { return _Name; }        set { _Name = value; }    }    publicdecimal Price    {        get { return _Price; }        set { _Price = value; }    }}   First, we'll create a Product list and fill it with products:   List<Product> products = GetAllProducts();   Now, let's say you want to filter the products, and only get products that have a price of more than $40.  You can filter the list by using the FindAll() method, using anonymous delegates instead of predicates:   products = products.FindAll(delegate(Product p) { return p.Price > 40; });   You can sort a generic list the same way.  Usually, to sort a custom class, you'd have to have your class inherit from the IComparable interface, and implement your own CompareTo method.  But using anonymous delegates, you can use the Sort method any way you want with just a single line of code. This will sort the list by Name ascending:   products.Sort(delegate(Product p1, Product p2) { return p1.Name.CompareTo(p2.Name); });   So there you have it. Using anonymous delegates, you can sort and filter an entire generic list using only two lines of code.A few more examples:   //Filter list to only get products that start with the letter Aproducts = products.FindAll(delegate(Product p) { return p.Name.ToLower().StartsWith("a"); });//Filter over a price rangeproducts = products.FindAll(delegate(Product p) { return (p.Price > 20 && p.Price < 60); });//Sort by Name descendingproducts.Sort(delegate(Product p1, Product p2) { return p2.Name.CompareTo(p1.Name); });

Tags: ,

Check out Matt Bohn's Article in asp.net PRO Magazine

by Todd Knowlton February 25, 2009
Fusionary Matt Bohn has the cover article in the March 2009 issue of asp.net PRO magazine. Check it out at http://www.aspnetpro.com/PDF/Issues/aspMAR2009.pdf  

Tags:

Search Blog

WELCOME TO OUR BLOG

Fusionovation is an industry blog written by Smooth Fusion team members that serves to inform marketers of cutting-edge digital topics and trends.

Smooth Fusion specializes in helping marketers with the planning and implementation of digital campaigns and ongoing programs. We are a trusted partner to marketing agencies and corporate marketers worldwide, delivering our unique blend (or fusion) of technical expertise and understanding of the needs of marketers.

Our team is made up of consultants, project managers, software engineers, developers, designers, and quality assurance specialists. And what we all have in common is experience using technology to empower marketers. Learn more about Smooth Fusion.