Hugoware

The product of a web developer with a little too much caffeine

Archive for May 2010

Cobalt Beta – jQuery Style MVC View Templating!

leave a comment »

In a recent blog post I shared a preview of the Cobalt project I’ve been working on. Today, the source code has been uploaded to git-hub and the first beta binaries are being released!

Not sure what Cobalt is? Watch a screencast showing how you can use Cobalt in your MVC projects.
Watch the video now!

If you’ve seen any of my previous blog posts then you realize I’m not much of a fan of the current way to populate templates in ASP.NET MVC. I’ve tried a handful of different ways to improve the experience but so far nothing really felt like an improvement.

Cobalt uses CSS selectors to find and update content, much like the way that jQuery works. Cobalt works *with* ASP.NET MVC (and WebForms) so you can include it in an already existing project and use it right away!

So what does Cobalt look like? Here is an example of an MVC View…

<%@ Page Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<ProductDetail>>" %>
<%  
    this.Ready(() => {

        //select by tag names
        this.Find("form")
            .Attribute(new {
                action = this.Url.Action("CheckOut")
            });
        
        //find and set values for elements
        string current = this.Find("h3").Text();
        this.Find("#title").Text(current.ToUpper());
        
        //select classes and certain pseudo selectors
        this.Find(".list :even").AddClass("alt-item");
        
        //create new elements on the fly
        var link = this.Create("<a/>")
            .Text("Read About Us")
            .Attribute("href", this.Url.Action("AboutUs"));
        this.Find("p").Append(link);
       
        //create custom elements (like CustomControls)
        Stylesheet sheet = new Stylesheet("~/site.css");
        sheet.AddToPage();
        
    });
    
%>

<html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <form method="post" >
            <h3>Temp Title</h3>
            <p>The description goes here</p>
            <ul class="list" >
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
                <li>Item 4</li>
                <li>Item 5</li>
            </ul>
        </form>
    </body>
</html>

You can see that much like jQuery we have to queue up the work we need to execute once the document is ready.

I have a lot of documentation to write and a lot of screencasts to record, but don’t forget about the preview video which should get you started. For now, here are a list of the more important details.

The Important Stuff!

  • You must call CobaltManagement.Initialize() in your Global.asax file in the Init method (just override it and call it).
    public override void Init() {
        base.Init();
        CobaltManagement.Initialize();
    }
    
  • Cobalt uses HtmlAgilityPack to handle parsing of html content. I’m not happy with the framework so it will be one of the first things to be phased out, but for now you need to make sure to download it if you get the source code instead of the binaries.
  • You must use this.Ready from your pages and controls to wrap your commands. Otherwise your commands will run before the document is ready and fail.
  • Cobalt is aware of context, so if you use this.Find within a UserControl then you’re only going to select elements within that control. If you need to access the Page level from a UserControl then you can call this.Page.Find to change the scope of the command.
  • Cobalt supports a decent amount of selectors. Below is a list of currently available options.
    • Combinators: ‘ ‘, >, +
    • Shortcut Attributes: #elementId, .cssClass, $elementName
    • Attribute Matching (ex. [@name=’value’]): equals (=), starts with (|=), ends with ($=), contains (~=)
    • Pseudo: first, last, even, odd, nth(#), lt(#), lte(#), gt(#), gte(#), text, password, button, checkbox, radio, submit, file

Keep in mind this is very much beta code – I was literally working on changes today :). If you’re feeling brave then download the source and dig right in!

Download Beta

Cobalt (Source Code)

Advertisements

Written by hugoware

May 31, 2010 at 11:38 pm

Cobalt MVC Preview!

with 3 comments

Lately, I’ve been working a lot on my project Cobalt which is, more or less, jQuery for server side ASP.NET MVC views. I’ve shown some code examples before but today I have a screen cast of some of the code in action.

Watch the video now!

Hopefully, I’ll have some code released in the next week or two, but for now feel free to give thoughts and feedback!

Written by hugoware

May 27, 2010 at 9:09 am

MVC Templating – jQuery Style!

with 3 comments

I’ve messed around with a variety of ways to make MVC templating better but I’ve never really been satisfied with any of my solutions until now.

One of the things that I really like about jQuery is that it allows for better separation of markup from code since you can use CSS selectors to find and change elements on the page. ASP.NET MVC requires server side blocks of code to be mixed into the markup to display content.

The other day I started working on a new project I’ve named Cobalt – A jQuery style, context aware templating framework for ASP.NET MVC. I’m not quite ready to release the code but I wanted to share the idea in advance.

Note: When I say “jQuery Style”, I mean method chaining with css selectors – You can’t use $()… sorry 🙂

Let’s pretend we have the following markup

[Index.aspx (Markup)]

<%@ Page ... %>
<html>
    <head>
        <title>Untitled</title>
    </head>
    <body>
        <h1>Title</h1>
        <div class="content">
            <p></p>
            <ul></ul>
        </div>
        <a id="back" >Previous</a> | <a id="next" >Next</a>
    </body>
</html>

Using Cobalt, we can use jQuery style code to select the correct elements and update content in server side code at the top of the view.

[Index.aspx (Server Code)]


//select tags by their names
this.Find("h1")
    .Text("My Page");

//select tags by name
this.Find("a")
    .Attr("href", this.Url.Action(link.Text())
    .Css(new { color = "#f00" });

//find by ID
this.Find("#back")
    .Remove();

//use other selectors
this.Find(".content > p")
    .Html(this.Model.PostContent);

//select classses and children
this.Find(".content > ul")
    .Remove();

//or perform sub queries
this.Find(".content", content =>
    content.Find("strong")
        .Text(bold.Text().ToUpper())
            .AppendTo(content)
            );

Keep in mind, this code is part of the view and not in a code behind file.

Of course, this view could probably be just as easily updated using a Model and assigning values using server side blocks of code, but consider some of the advantages of keeping our code separated.

  1. Markup stays free of server side code blocks so it is easier to pull the content from external resources (for example a database)
  2. If the markup is constantly being changed by another team member (for example a designer) we can avoid tinkering with the new HTML and instead make changes to our selectors (if even needed).
  3. Many web developers are familiar with CSS selectors – The template could be understood by other team members and developers regardless of programming language choice.

Being Context Aware

The context of a selector is another important part of Cobalt. If you’re working in a UserControl you might changes to stay within the context of the control. At the same time, you might want some of your commands to change other parts of the page.

[SomeControl.ascx]

<@ Control ... %>

<h3>Latest Tweets</h3>
<ul class="tweet-list" ></ul>
<a href="http://www.twitter.com/hugoware" >Follow Me!</a>
<% =this.Html.ActionLink("Rendered Link", "Index") %>

When you use the this.Find(...) command, the actions are queued up and executed only for the calling control. That said, you can use the this.Page or the this.Parent properties to change the context (and scope) of a command.

[SomeControl.ascx (Server Code)]


//context stays inside of the UserControl
this.Find("ul.tweet-list")
    .Html(this.Model.Tweets);

//context stays inside of the UserControl
this.Find("h3")
    .Text("Follow Me!");

//finds both links (static and rendered)
this.Find("a")
    .Attr("href", this.Url.Action("Home"))
    .Text("changed!");

//context changes to the page level
this.Page.Find("head")
    .Append(this.Model.Stylesheet);

//updates the title in the page
this.Page.Find("title")
    .Text("Changed the title!!");

//never finds the title (context is in the control)
this.Find("title")
    .Text("Title not changed!");

Again, this might be a little extra code in some cases, but we are also able to access elements all over the page without needing to apply special WebControls or wire up to the Page life cycle.

It is worth pointing out that both links will be discovered by the a selector since the actions aren’t actually invoked until after the page is rendered. This means you can use MVC like you normally would and still use Cobalt to find and change elements. In fact, as far as I can tell this should work with WebForms as well as MVC, but I’d have to test it before I could say how well it works.

Work In Progress

This project is only a few days old right now but is already coming along very well. I’ll be posting some code soon but till then feel free to share any ideas you have.

Written by hugoware

May 17, 2010 at 11:56 pm

ASP.NET 4.0 New Html.Encode Syntax

leave a comment »

This post should probably be filed under ‘problems that no one will actually need to Google’ but here goes anyways.

Maybe I’m weird, but I tend to write server side blocks and bindings in ASP.NET like so…


<h1><% =this.Model.Title %></h1>
<span><% =this.Model.Posted.ToShortDateString() %></span>
<div><% =this.Model.Content %></div>

All of my equal and pound signs are placed directly next to the content being written — not the actual server code block. No big deal right? Well… maybe not quite the case in the new ASP.NET…

I started using the new ASP.NET 4.0 stuff today… yeah, I wasn’t much of an early adopter this time… the IDE turned me off too much.

Anyways, when I tried the new HTML encoding syntax I got the following message…

Invalid expression term ‘:’

Apparently, few people write their blocks the same as I do… After poking around for a moment I realized that the parser just simply did not like the colon to be anywhere else except for directly by the percent sign. So just remember…

<%: "OK!" %>
<% :"Crash!" %>

Also, if you do this in Visual Web Developer (Express) then you’ll get the message ‘BC30035: Syntax error.’… but it is the same problem…

Written by hugoware

May 11, 2010 at 8:20 pm

Sienna MVC

leave a comment »

This last week has been a time of mourning for me but I have reached the acceptance phase. Now, that I’m ready to move on I can share some code I’ve been working on.

I’ve blogged a lot before about using WebForms and more recently using WebControls with ControlAdapters in MVC, but for the most part it was just messing around with small sections at a time. Tonight I published my templating framework on GitHub called Sienna.

Before you read further realize that this is not WebForms in MVC. This is WebControls in MVC — or basically the templating and using code behinds for View logic.

I might be alone on this but I am having a hard time of letting go of using code behinds for separating code from the page markup. No matter how simple a view is server side blocks of code are ugly. They are difficult to read and even harder to refactor, which is something that code behind files still excel at.

Sienna makes it so you can create new instances of Pages, assign to properties and then return them as ActionResults. To take it a step further, Sienna uses ControlAdapters to render cleaner markup and avoid the junk IDs that ASP.NET typically spews out… yes, and it drops the ViewState as well 🙂

Let’s look at an example of how Sienna works. Below is a sample page from a blog engine web application.

[/Views/Index/BlogPost.aspx]

<%@ Page Language="C#" 
    CodeBehind="BlogPost.aspx.cs" 
    Inherits="Site.Views.Home.BlogPost" %>
<html>
    <head runat="server">
        <title></title>
    </head>
    <body>
        <h1 id="name" runat="server" />
        <div id="posted" runat="server" class="date" />
        <div id="content" runat="server" />
        
        <form id="commentBox" method="post" action="[controller:Home][action:Comment]" runat="server" >
            <input id="email" runat="server" type="text" _id="email" _name="email" />
            <textarea id="comment" elementname="comment" runat="server" ></textarea>
        </form>
    </body>
</html>

[/Views/Index/BlogPost.aspx.cs]

using System;
namespace Site.Views.Home {

    //displays a blog post
    public partial class BlogPost : System.Web.UI.Page {

        //the post to publish display
        public Post Post { get; set; }

        //display the content
        protected override void OnLoad(EventArgs e) {

            this.Title = this.Post.Title;
            this.name.InnerText = this.Post.Title;
            this.content.InnerHtml = this.Post.Content;
            this.posted.InnerText = this.Post.Created.ToShortDateString();

            //add the classes for the date
            this.posted.AddClass("newest-post");

            //handle showing comments or not
            this.commentBox.Visible = Visitor.IsLoggedIn;

        }

    }

}

This might be a small amount of code but there are a lot of things to explain about it. I’ll focus in some of the more relevant parts.

  • Instead of using the built-in WebControls in ASP.NET we are using regular HTML controls that have been marked to be handled by the server.
  • Because ‘id’ and ‘name’ have special meanings to ASP.NET, we can use _id and _name to define the actual IDs to display, otherwise, no ID is shown. This allows a control to be available to the code behind using one ID and then rendered using another (or none at all). You can also use elementid, displayid or actualid if you do not like using underscores.
  • Attributes like href and src can use a special format that will be parsed by a URL helper in the background at render time. The format is [name:value][otherName:otherValue].
  • Because we use HTML elements for the template, we have access to the InnerHTML and the InnerText properties to assign values. Additionally, Sienna includes additional HTML helper methods for other common functions.
  • This example shows a normal Page as the type but you can use anything that inherits from the Page type — including ViewPages, which will give you access to the Url and Html helpers. If you aren’t using a ViewPage, the UrlHelper and Controller instances are stored in the Page.Items property.

Now, how would you actually use this view from a controller? Well, it is really quite easy…

//shows the latest blog post
public ActionResult Index() {

    //get the content
    BlogPost post = BlogPostRepository.GetLatest();

    //create the view and assign the value
    var view = this.CreatePage<Views.Home.BlogPost>();
    view.Post = post;

    //show the page
    return this.Page(view);

}

And that is it – The PageResult is returned and executed normally and the final result is nice and clean HTML output.

<html>
    <head>
        <title>My Post</title>
    </head>
    <body>
        <h1>My Post</h1>
        <div class="date newest-post" >10/15/2009</div>
        <div>
            <!-- snip... -->
        </div>
    </body>
</html>

You can also use this same approach to assign directly to properties on the page. For a second example, let’s say our code behind actually looked like the following.

using System;

namespace Site.Views.Home {

    //displays a blog post
    public partial class BlogPost : System.Web.UI.Page {

        //the name of the post to show
        public string Name {
            get { return this.name.InnerHtml; }
            set { 
                this.name.InnerHtml = value;
                this.Title = value;
            }
        }

        //the content to display
        public string Content {
            get { return this.content.InnerHtml; }
            set { this.content.InnerHtml = value; }
        }

        //the day the blog post was created
        public DateTime Posted {
            get { return DateTime.Parse(this.posted.InnerHtml); }
            set { this.posted.InnerText = value.ToShortDateString(); }
        }
    }
}

The nice thing about this approach is that the View defines which properties need to be encoded by using the InnerText or InnerHTML properties. It also allows us to assign other types like DateTime but then the View determines how to use it. Depending on how you look at it, this approach replaces the ViewModel by filling both roles at once.

Unfortunately when we create this control the links between the HTML elements and the properties are not immediately available. That doesn’t take place until after the page starts to render. So, to solve this we can assign to the Init event as part of when we create the Page.

//shows the latest blog post
public ActionResult Index() {

    //get the content
    BlogPost post = BlogPostRepository.GetLatest();

    //show the page
    return this.Page<Views.Home.BlogPost>(page => {
        page.Name = post.Title;
        page.Content = post.Content;
        page.Posted = post.Created;
    });

}

And our page is correctly created and rendered into view!

Technically, this whole approach should work with existing WebForms pages by allowing you to use MVC Controllers and Routes and then returning the correct page automatically. Of course, this hasn’t been tested and I really don’t recommend that you use it that way… but still interesting to think about 🙂

Sienna works with MVC projects so you don’t need to start anything over. Simply add the files to your project, generate the Browser definitions file (which is part of the ControlManagement class in Sienna) and off you go!

[Source Code: Sienna]

So go try it out and let me know what you think!

Written by hugoware

May 9, 2010 at 11:08 pm