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
@functions{

    // 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;}        
</style>
@{

    // 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);
        }
        else
        { 
            // the model is valid - proceed with it to a db or whatever
            view ="<div>Valid!</div>";
        }
    }
    else
    {
        view = form.Html();
    }    
}
@Html.Raw(view)

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

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>

@Html.Raw(form.ClientSideScript())

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.

Advertisements

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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s