Separating html and logic in Razor (WebPages or Umbraco macroscript)

Mixing logic and html can easily end up with messy, hard-to-maintain code. In MVC it’s easy to separate the parts with the controller / view-separation. But how to do it nicely in WebPages or in an Umbraco macroscript?

Ultimately I want my Razor to be free from

  • variable assignments other than for loop iterators
  • function calls other than formatting and html helpers
  • usage of data outside of the “ViewModel”

I have some WebPages and Umbraco projects with some quite advanced razor code and I’ve been having many doubts about how I mix logic in my razor code. I try to separate it, most often by placing logic at the top, but still using Razor (with helpers or RenderPage by all means). After re-thinking some about the @functions ability in Razor and found out about the overridable InitializePage function I feel I now have a better more solid structure to use.

Update: I recommend do not use this too extensively
The “functions” approach is nice, but also consider the simpler way just to have an initialization section in the top of the script – still separating C# from actual view. See this post for an example.

And if you have extensive pure C# move it to a base class which you inherit your script from.

The idea is simply this : remove all logic (but necessary iterations and some conditions) from the razor, and place it in the @functions part (in the InitializePage function) together with ViewModel properties. The ViewModel properties should contain all data that the view part needs to be able to render the page / the macro. And the view part should not access anything else than the ViewModel properties:

@* --- The logic-less view part: --- *@


@* --- The controller / viewmodel constructor part: --- *@


  // the properties of the view model:
  public string SomeProperty {get; set;}

  // taking care of post data and constructing the view model:
  protected override void InitializePage()
    // make up the "ViewModel" properties
    SomeProperty = "some data";

Advantages with this approach

  • A clear separation of view and logic (not as clear as having them in separate files tho)
  • The logic is pure C#-code, no risk of doing mistakes due to misplaced @’s (and missing code blocks)
  • The code is a big step towards MVC, and the full step will be quite easy later on if necessary
  • Minimal added whitespace in page source

Helpers are perfectly fine to add to this – but just as with the view code, I think any logic but view logic should be left out of them.

A remake of my “old skool” contact form sample

I wrote a contact form razor sample quite a while ago, guilty of mixing logic into the view. However I’m not the only one😉, a sample at

Here’s a better (I think) remake, using the initializepage-structure:

<h2>Contact form</h2>

   <form action="#" method="post">
       <label for="name">Name:</label>
       <input id="name" name="name" value="@PostedName"/>
       <label for="message">Message:</label>
       <textarea id="message" name="message">@PostedMessage</textarea>
     <input type="submit" value="Post message"/>

  public bool ShowForm {get; set;}
  public bool ShowMessage {get; set;}      
  public string Message {get; set;}
  public string PostedName {get; set;}
  public string PostedMessage {get; set;}
  protected override void InitializePage() 
    if (!IsPost) 
       ShowForm = true;
       ShowMessage = false;
       PostedName = Request["name"];
       PostedMessage = Request["message"];
       var IsValid = (!string.IsNullOrEmpty(PostedName) &amp;&amp; !string.IsNullOrEmpty(PostedMessage));
       if (IsValid)
         var bodyText = "Message from " + PostedName + Environment.NewLine + PostedMessage;
         umbraco.library.SendMail("","","New message", bodyText,false);
         Message = "Thank you " + PostedName + " for posting a message";
         ShowForm = false;
         ShowMessage = true;
         Message = "You need to enter both name and message";
         ShowForm = true;
         ShowMessage = true;

Public properties or private fields?
The public properties could be private fields without any problem (in these samples), the reason I choose public properties is that I like to resemble the MVC structure as far as possible.

Responding to an ajax-post

This structure also makes it really easy to handle and respond to ajax posts to the same form (this can only be done in a pure WebPages razor, not Umbraco macro as that does handle the Response output the same way) :

    ... in the validated post part ...
    if (IsAjax)
        Json.Write(new {
          postValid = true,
          message = Message
          }, Response.Output);

In Umbraco the options for ajax are to either to run razor script outside of the Umbraco context (use WebPages + add reservedpath in web.config) or to make a separate “ajaxresult-template” with a razor call:

Bonus: posting the form with ajax in Umbraco

Using this method you can return json directly from your razor script in Umbraco. The tricky part is we dont want to return the surrounding template parts, and for simplicity we want to use code in the same razor script as as we already are in.

Add a template – call it AjaxRazor – which will be responsible for rendering the razor without anything but the script result (we add an if IsAjax condition to have some kind of security against unintended run script files, please add more security checks for posts on a live site):

<%@ Master Language="C#" MasterPageFile="~/umbraco/masterpages/default.master" AutoEventWireup="true" %>

<asp:Content ContentPlaceHolderID="ContentPlaceHolderDefault" runat="server">
  <umbraco:macro language="cshtml" runat="server">
    @if (IsAjax){
      var path = Request["path"];
      if (!path.StartsWith("~")) { path = umbraco.IO.SystemDirectories.MacroScripts + "/" + path;}

Now it’s possible to run any razor script using the url /AjaxRazor?path={path-to-script}

Next make the form post it’s contents to the template, with the razor script path as a querystring parameter, we get that path with the help of the page property VirtualPath:

  Json.Write(json, Response.Output);
 <script type="text/javascript" src=""></script>
 <script type="text/javascript">
  $(document).ready(function() {
  $('form').submit(function() {
  return false;

 <form method="post" action="#">
 <input type="text" name="name"/>
 <input type="submit"/>
 if (showMessage)
 private bool showOnlyJson;
 private bool showMessage;
 private bool showForm;
 private string message;
 private object json;
 private string ajaxPostPath;
 protected override void InitializePage()
      var postedName = Request["name"];
      message = "Thanks for posting";
      if (IsAjax)
       showOnlyJson = true;
       json = new {message=message, name = postedName};
       showMessage = true;
       showForm = false;
       showForm = true;
       ajaxPostPath = "/AjaxRazor?path=" + VirtualPath; 

Umbraco v5

I believe this approach still might be useful in Umbraco v5. It should likely not be recommended as an option for advanced solutions, but for simple forms (and advanced navigations) I think its suitable. And even if it’s not suitable it’s a good step towards controllers and viewmodels.

A Razor application within an Umbraco site (notes from a current project)

We’re in the middle of re-developing a web application that previously was made as an Webforms app. The current requirements is to integrate the application into an Umbraco 4.7 site, to use a new design (delivered as a html, CSS & js prototype) as well as to change some of the underlying database workings.

We decided to go for an WebPages, aka Razor, aka WebMatrix, solution in this case. It’s a very straight forward, close to the metal, way of coding for the web, and we’re very happy with our experiences so far.
When we develop the application we work completely outside of Umbraco, within an Asp.Net Razor website in Visual Studio (and sometimes in WebMatrix actually). The application itself is completely independent of Umbraco context.

So, we test run and debug our application within Visual Studio, then we deploy all changes just by FTP’ing the files to the Umbraco staging site where our customer can try it within their site. It’s a very fluent and flexible developing process.

The most important parts of the application

  • A set of (~10) cshtmls that represents each different page (url) of the application.
  • A wrapper content page in Umbraco for each of the app pages, with the path to It’s corresponding cshtml as a property, RenderScriptPath.
  • A wrapper template in Umbraco, which is a copy of the standard content template for the whole site, but with one important instruction:
    <umbraco:macro runat="server" language="cshtml">
    @if(Model.RenderScriptPath!="") {

    this call is rendering the actual application page within the site layout.

  • A service cshtml for serving Ajax calls
    @if (OurApp.CheckLogin() && IsAjax)
      // routing each call to the right function / json result
      var action = Request["action"];
      if (action=="products") {
        var category = Request["category"];
  • A corresponding – empty – template with just this code to render the service cshtml:
    <umbraco:macro runat="server" FileLocation="/macroscripts/ourapp/ajaxservice.cshtml" />
  • An UmbracoMockLayout.cshtml to make the off-site app look nice, with references to the necessary CSS, images and JavaScript files
  • An _PageStart.cshtml to automatically use the above layout from each of our .cshtml-pages. We do not copy the _PageStart-file to the Umbraco site (and even if we did it would not be run).
    @{Layout = "_UmbracoMockLayout.cshtml";}
  • Businesslogic, in a separate project
  • PetaPoco, as the micro Orm layer for the database
  • JavaScript, CSS and image files. In the same paths in the separate project as in the Umbraco site
  • Dewd, as a way for our Umbraco editors to edit some datatables directly within Umbraco

Umbraco content and asp.Net membership

The application is not entirely disconnected from Umbraco (but almost). There are texts on a few of the pages that is editable from within Umbraco, and used with the common Model.Property syntax. Otherwise the application is just using the Umbraco site navigation and designs. Also the app is using the same membership as the site.


In this project we’re using techniques and products we really like and find to be very efficient and high quality. The resulting application is soon to be launced, so we cannot say much about how it ends up:-), but it’s looking good so far, and we can definitively say that the development process has been unusually friction-free and fast.

FrĂ„n noll till en komplett webbplats med Umbraco CMS pĂ„ mindre Ă€n en timme

Umbraco Àr ett gratis opensource-CMS byggt pÄ Microsofts ASP.NET ramverk. Det Àr byggt för att vara lÀtt att förstÄ och anvÀnda, samt enkelt att bygga ut. Det Àr ett av de 3 mest populÀra nedladdade programvarupaketen i Microsofts Web Platform Installer och det anvÀnds över hela vÀrlden för i stort sett alla typer av webbplatser.

Genom att anvĂ€nda gratisverktyget WebMatrix sĂ„ Ă€r det vĂ€ldigt smidigt att installera Umbraco pĂ„ din dator – och det finns dessutom webhotell som erbjuder billig hosting för WebMatrix-sajter med mycket enkel publicering. Detta innebĂ€r att du kan ha en egen webbplats med de smidiga redigeringsmöjligheter som ett professionellt CMS erbjuder uppe och igĂ„ng ute pĂ„ internet pĂ„ mindre Ă€n en timme.

Tror du mig inte? HĂ€ng med…

1. Ladda ned och installera WebMatrix

GĂ„ till och installera den senaste versionen av WebMatrix.

2. Skapa en Umbraco webbplats frĂ„n WebMatrix “Web Gallery”

NĂ€r du startar WebMatrix fĂ„r du som alternativ att starta en ny webbplats frĂ„n “Web Gallery”. I galleriet hittar du Umbraco. VĂ€lj det och skriv in ett namn för din webbplats, följ sedan guiden för att ladda ned och installera Umbraco:

3. Kör Umbraco-installationen

NĂ€r WebMatrix har installerat Umbraco kommer du att Ă„tergĂ„ till redigeringsdelen i WebMatrix. Klicka pĂ„ lĂ€nken till din webbplats (site) “URL : http://localhost:nnnn&#8221; för att öppna din lokala webbplats i din webblĂ€sare:

Första gĂ„ngen du öppnar din lokala webbplats kommer Umbraco att köra sin installationsrutin. DĂ€r vĂ€ljer du vilken typ av databas du vill anvĂ€nda, samt det anvĂ€ndarnamn och lösenord du vill ha, dessutom fĂ„r du om du vill vĂ€lja “Starter kit” och “Skin” för din webbplats.

Jag rekommenderar dig att följa installationsrutinens föreslagna alternativ nÀr sÄdana finns, vÀlj sÄledes Sql CE som databas, det innebÀr att du inte behöver nÄgon installerad databasserver pÄ din dator, Sql CE anvÀnder helt enkelt en fil som kommer att sparas i din webbplats filstruktur.

NĂ€r du fĂ„r vĂ€lja Starter kit och Skin föreslĂ„r jag att du vĂ€ljer “Simple Starter kit”, och det Skin som du sjĂ€lv tycker bĂ€st om.

4. Dags för det administrativa grÀnssnittet i Umbraco

NÀr Umbracos installationsrutin Àr fÀrdig sÄ Àr det dags att titta pÄ Umbracos anvÀndargrÀnssnitt för första gÄngen.

LĂ€gg mĂ€rke till att du har en trĂ€dvy med en “nod” för varje sida pĂ„ din Umbracowebbplats. Klicka till att börja med pĂ„ noden “Sample website” som representerar webbplatsens startsida. Ändra pĂ„ nĂ„gra texter. NĂ€r du har Ă€ndrat och vill att Ă€ndringarna ska synas sĂ„ ska du klicka pĂ„ Publicera (Publish). DĂ„ kommer din lokala sajt att uppdateras och du kan se webbplatsen med dina Ă€ndrade texter:

Det Àr enkelt att vÀxla fram och tillbaka mellan Umbracos anvÀndargrÀnssnitt och din webbplats med hjÀlp av webblÀsarens flikar. Om du tappar bort din Umbraco-flik sÄ kan du alltid öppna den igen genom att öppna adressen http://localhost:nnn/umbraco/ (nÀr nnn Àr det portnummer som WebMatrix har valt Ät dig, du hittar det under Site i WebMatrix).

Du har nu WebMatrix och din webbplats pĂ„ din egen dator och det finns ingen möjlighet att komma Ă„t den utifrĂ„n. Webbplatsens filer finns din mapp “Mina dokument” och undermappen “My Sites”. NĂ€r du har stĂ€ngt WebMatrix kan du komma Ă„t din webbplats igen genom att öppna WebMatrix och sedan vĂ€lja din webbplats under “My Sites”.

5. Ut med webbplatsen pÄ internet

NÀr du har redigerat din webbplats och vill att den ska synas pÄ internet sÄ behöver du hitta ett webbhotell (webbhost).

Du kan göra det med hjĂ€lp av en lĂ€nk i WebMatrix, under Publish – Find Hosting, eller anvĂ€nda ett webbhotell som du kĂ€nner till sedan tidigare.

Jag testade “Appliedi” nĂ€r jag skrev den hĂ€r artikeln. Deras installation var vĂ€ldigt enkel med stöd för funktionen WebDeploy. Appliedi Ă€r dessutom gratis i tre mĂ„nader (dĂ€refter $5 i mĂ„naden).

NÀr du har bestÀllt testpaketet ska du fÄ ett epostmeddelande med dina inloggningsuppgifter.

Kopiera dessa uppgifter och klistra in dem i WebMatrix “Publish Settings”

6. Publicera!

NĂ€r du har lagt in dessa uppgifter sĂ„ kan du publicera din webbplats, klicka pĂ„ “Publish”. Det kommer att ta nĂ„gra minuter eftersom en fullstĂ€ndig Umbracoinstallation innehĂ„ller ganska mĂ„nga filer. NĂ€r publiceringen Ă€r klar kommer du – och alla andra – att komma Ă„t din sida pĂ„ Internet!

Att redigera innehÄllet

BÄde din lokala installation och den pÄ ditt webbhotell har allting som behövs bÄde för att visa webbplatsen och för att redigera den med Umbracos administrativa grÀnssnitt. Förutom publiceringsrutinen sÄ finns det ingenting som kopplar ihop din lokala installation med den som finns pÄ Internet. Det innebÀr att om du Àndrar innehÄll lokalt sÄ kommer det inte att synas utÄt om du inte publicerar om webbplatsen. Men det innebÀr ocksÄ att du kan anvÀnda din lokala kopia för att testa olika idéer, och sedan lÀgga in dem pÄ din publika webbplats nÀr du Àr nöjd med resultatet, helt enkelt genom att jobba i det administrativa grÀnssnittet dÀr ocksÄ.

PÄ samma sÀtt som att din lokala kopia Àr Ätkomlig via localhost://nnn/umbraco/ sÄ kommer du Ät din webbplats pÄ internet genom att gÄ till adressen . Inloggningsuppgifterna Àr desamma som du valde nÀr du gjorde umbracoinstallationen.

Lycka till!

LÀs mer om Umbraco pÄ och om du har frÄgor eller kommentarer sÄ fÄr du gÀrna stÀlla dem hÀr. Om det finns intresse sÄ kommer jag Äterkomma med fler artiklar pÄ svenska om Umbraco.

Jag kan ocksÄ varmt rekommendera Umbraco-forumet.

The MvcMiniprofiler nuget in WebMatrix (WebPages) [5 minutes]

The MVC3-guys gets a lot of fun tools, but what about us that sometimes prefer WebPages for getting things done on the web? Mostly it’s cool since we’re on the same good solid Asp.Net platform. The MvcMiniProfiler for example. I just read Scott Hanselman’s introduction to it and wanted to try on a WebPages site. It worked fine and looks very useful – easily profile the server side of any WebPages web app.

First – create a new Web Site (Razor) in Visual Studio or create a new site from template in WebMatrix and choose the StarterSite template.

Then add the MvcEasyProfiler Nuget MiniProfiler by opening the Package Manager Console in Visual Studio (Tools-Library Package Manager, Install-Package MiniProfiler). Or start your site in WebMatrix and go to the _admin page, first create a password, and then search for MiniProfiler (choose Default(all) as source for packages). Look for the most recent version (1.6 today). Install it.

Next add a new file called _PageStart.cshtml in the root of your web site. That page runs for every page request on your site. Using the RunPage() we divide code to be run before and after page code execution. Add the following code:

    if (Request.IsLocal)

Then open the _SiteLayout.cshtml page. Add the following code just above the head end tag to include the necessary js scripts on your pages:

    <script type="text/javascript" src=""></script>    

After that you have the profiler running and you can test it by opening any page.

When you like to test a particular piece of code enclose it within a profiler step like this:

@using MvcMiniProfiler
    using (MiniProfiler.Current.Step("Doing complex stuff"))
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Welcome to my Web Site!";

And you get a nice window top left on your page with profiling data:

Read the Hanselman post to dive deeper into the possibilities.

A first look at SlickGrid with read, insert and update (in WebMatrix)

A few days ago I had a quick look at Flexigrid and I planned to continue with it to enable updates. However when I searched a bit further I got recommendations to use SlickGrid instead and so I did. As with my Flexigrid post this post is based on what I learned in a short time – if you are looking for a in depth / best practices sample you should indeed look at the library authors samples instead.

My first impression with SlickGrid is that it is a very good looking grid and it was easy to get a read and update solution up and running with very little code.

Another strength of SlickGrid is that it is possible to use a DataView model to handle the data. However that’s not something I have experimented with yet, and this sample is using a straight serverdata – grid path.

Edit (2011-12-12) to make it use the latest SlickGrid I updated my code pretty much + now also allows insert (so full CRUD, yay…)

Here’s how I did it:

The data comes from a simple Sql CE 4 db-table with the columns id (pk+identity), name (nvarchar 100), description (nvarchar 100) and somevalue (int). To create the SlickGrid I initialize it with a columns array, an options object, a data.cshtml that returns a Json object from a database read and takes post data for database insert or update.

Here’s how the html & javascript code looks like for my page (default.cshtml):

    Layout = "/_layout.cshtml";
        <script type="text/javascript">
    $(document).ready(function () {
        var grid;
        var columns = [
            { id: "name", name: "Name", field: "name", editor:TextCellEditor, resizable:false, width:100, rerenderOnResize:true},
            { id: "description", name: "Description", field: "description", editor:TextCellEditor, resizable:false, width:100, rerenderOnResize:true},
            { id: "somevalue", name: "Some value", field: "somevalue", editor:IntegerCellEditor, resizable:false, width:100, rerenderOnResize:true},
            { id:"id", name:"Delete", field:"id",
              formatter: function (r,c,id,def,datactx) {
                  return "<a href='#' onclick='removeClick(" + id + "," + r + ")'>x</a>";

        function removeClick(databaseId, gridRow) {

            var data = grid.getData(); 
            data.splice(gridRow, 1);


        var options = {
            editable: true,
			enableAddRow: true,
			enableCellNavigation: true,
			asyncEditorLoading: false,
            enableColumnReorder: false,                        
            autoHeight: true

        // Handle updates

        $.getJSON("/mygrid/data", success = function (data) {
            grid = new Slick.Grid("#myGrid", data, columns, options);            
            grid.onCellChange.subscribe(function (e, args) {
                if (typeof('undefined')
                    $.post("/mygrid/data/insert", args.item);
                    $.post("/mygrid/data/update", args.item);
            // Handle new row
            grid.onAddNewRow.subscribe(function(e, args) {
                var item = args.item;
                var column = args.column;

<div id="myGrid" style="width:400px;display:none;"></div>

The page is using jQuery and SlickGrid with editors plugin (included in the library samples). The css is both from jQuery UI and from SlickGrid.

Here are all the js- and css- files that’s included in the header section of the page (_layout.cshtml):

<!DOCTYPE html>

<html lang="en">
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/js/slickgrid/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
        <link rel="stylesheet" href="/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css" media="screen" charset="utf-8" />
        <link rel="stylesheet" href="/css/examples.css" type="text/css" media="screen" charset="utf-8" />
		<script src="/js/jquery-1.7.min.js"></script>
		<script src="/js/jquery.event.drag-2.0.min.js"></script>

        <script src="/js/slickgrid/slick.core.js"></script>
        <script src="/js/slickgrid/slick.editors.js"></script>
        <script src="/js/slickgrid/slick.grid.js"></script>


The data.cshtml:

    // Get Action from Url f ex /mygrid/data/insert /mygrid/data/update
    var action = UrlData[0];
    var db = Database.Open("data");
    if (IsPost)
        // Get Post data (convert null's to string or integer)
        var id = Request["id"];
        var name = Request["name"]??"";
        var description = Request["description"]??"";
        var somevalue = Request["somevalue"].AsInt();
        if (action=="insert")
            var sql = @"INSERT INTO item (name, description, somevalue) VALUES (@0,@1,@2)";
            var newId = db.GetLastInsertId();
        else if (action=="update")
            var sql = @"UPDATE item set name=@1, description=@2, somevalue=@3 WHERE id=@0";
            var data = db.Execute(sql,id,name,description,somevalue);
        else if (action=="delete")
            var sql = @"DELETE FROM item WHERE id=@0";
            var data = db.Execute(sql,id);
        var sql = "SELECT id, name, description, somevalue FROM item";
        var data = db.Query(sql).ToList();        


A first look at Flexigrid (using it with WebMatrix and Json)

We all need a nice grid to display data from time to time. I found out at Stackoverflow that Flexigrid has some popularity and the images I saw of Flexigrid in action impressed me.

This is a brief introduction post describing a way to use it for basic display of data in a WebMatrix (WebPages) web site. (I soon need the update functionality, and I hope I’ll be able to try that out and blog about in a few days.)

Let’s say we have a datatable with the columns id, name and address. We can retrieve the data with the standard WebMatrix.Data library and display it with the WebGrid helper this way:

  var db = Database.Open("myConnection");
  var sql = @"SELECT * FROM items";
  var data = db.Query(sql)
  var grid = new WebGrid(data);

It works, but is not exactly pretty:

If we use Flexigrid instead we get a much nicer result:

To accomplish this we need the flexigrid js and css files from the Flexigrid site.

I downloaded the zip, and extracted the two folders js and css to the root of my web site. Then I added reference to them and to jQuery in my demo page:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>Flexigrid demo</title>
    <script src=""></script>
    <script src="js/flexigrid.pack.js"></script>
    <link href="css/flexigrid.pack.css" rel="stylesheet" type="text/css" />

The Flexigrid needs an empty table tag and is initialized with a javascript function – together with information about the data columns, behaviours and looks of the grid.

I used a Flexigrid-sample and only changed it slightly to handle my columns (id, name, address) + the url for fetching the data.

The code is pretty self explanatory:

<table id="flex1" style="display: none">
<script type="text/javascript">
        url: '/data.cshtml',
        dataType: 'json',
        colModel: [
            { display: 'id', name: 'id', width: 40, sortable: true, align: 'center' },
            { display: 'name', name: 'name', width: 180, sortable: true, align: 'left' },
            { display: 'address', name: 'address', width: 120, sortable: true, align: 'left' }
        searchitems: [
            { display: 'name', name: 'name' },
            { display: 'address', name: 'address', isdefault: true }
        sortname: "name",
        sortorder: "asc",
        usepager: true,
        title: 'Names',
        useRp: true,
        rp: 15,
        showTableToggleBtn: true,
        width: 700,            
        height: 200

Fetching the data from
The data is being fetched with the help of an Ajax call, the url is specified in a parameter as in the code above. The data format is prefferably Json.

The Json needs to follow this format:


To construct the actual Json I added a data.cshtml file, where I’m using the WebMatrix Json helper over an anonymous object like this (the code here also includes paging functionality):

    var db = Database.Open("myConnection");
    var sql = @"SELECT * FROM items";
    var data = db.Query(sql).ToList();

    var pageLength = 15;
    var page = Request["page"].AsInt();   
    if (page==0) {page = 1;}

    var flexiGridItems = new
        total = data.Count,
        page = page,
        rows = from n in data.Skip(pageLength*(page-1)).Take(pageLength)
               select new { id =, cell = n }

    var json = Json.Encode(flexiGridItems);

That is all that’s necessary to get the nice Flexigrid up’n running in a WebMatrix (WebPages) web site.

In my next blog post I will explore the data updating functionality of Flexigrid.

Happy coding!

A first take on a C# HtmlFormHelper with client and server side validation

I have been looking for a pretty basic way of automating creation of Html Forms from C#. There’s ofcourse the MVC-way with scaffolding. But I’m not happy with that. I want to easily create my html tag setup in code and add / edit the fields and validation rules in a DRY way. If someone knows of an existing project of this kind, please let me know.

EDIT : HtmlFormsHelper has evolved into “DynaForms” (repo at GitHub), I will be blogging about it soon.

(A complete rewrite of this approach I made before.)

Also read the followup CRUD sample together with NancyFx and SisoDb.

So I wrote a ~300 Loc’s helper class with which this code is all that is necessary to create basic form which maps to a poco:

@using HtmlFormHelpers

    // Define the class somewhere
    public class MyClass
        public int Id { get; set; }
        public string Name { get; set; }
        public string Nickname { get; set; }
        public string EmailAddress { get; set; }
<style type="text/css">
    div.labelinput, div.submit {clear:both;}
    .labelinput label {width:100px;display:block;float:left;}
    .labelinput input {width:200px;display:block;float:left;}        

    // initiate the form helper object

    var form = new HtmlFormDescriptor("myclass-form");

    // Add some fields with optional validation rules, the helper will map the field names to the model field names

    form.Add("Name", required: true);
    form.Add("EmailAddress", labelText: "E-mail address", required: true, email: true);
    form.Add("Submit", type:"submit");

    // instantiate the model class

    var myClass = new MyClass();
    string view="";
    if (IsPost)

        // update and validate the model

        var validationResult = form.TryUpdateModel<MyClass>(Request.Form, ref myClass);
        if (!validationResult.IsValid)
            view = form.Html(myClass);
            // the model is valid - proceed with it to a db or whatever
            view ="<div>Valid!</div>";
        view = form.Html();

@* To enable client side validation using jQuery validate - just add librefs + one row: *@

<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>


Here’s a demo

Here’s the full source

Mind it’s still an early version and it’s far away from perfect, I publish it as I hope I can get comments, ideas and collaboration if someone is up to it. It’s easy to create a Gist fork and publish your own version of this little thing.

HtmlFormHelpers Gist

In my previous version I used FluentValidation for the server side validation, it’s still easy to use that instead of my simple validation code, but I missed a nice way to sync the FluentValidation validation rules with client side rules.