WebMatrix MVC-ishness with Simple.Data and FormHelpers for CRUD


Building upon what I started with in my last post – a controller like cshtml page in WebMatrix – I have now added some functionality which means I have a basic, but working (demo state), generic CRUD workflow mimicing important parts of a regular Asp Net MVC 3 application.

The code here is in an experimental state but I have decided to write about it already because both I think it works out well and also I would very much appreciate any feedback I can get.

In this next step after my initial MVC-ish lab in WebMatrix I add data handling with the use of Mark Rendles geniously dynamic SimpleData data access library.

Addressing some of the problems I experience with Asp Net MVC 3 programming

Long story short – I am trying to use good parts from popular dynamic languages MVC frameworks in my .net Web programming. Parts where MVC 3 still is rather clumsy. I dont want to tire you with a theoretic discussion just now – instead I want you follow me through a code explanation. (Look for the short theory at the bottom of this post if you like.)

Here goes:

The controller

Here’s what I do in my controller /person.cshtml for the “edit” action:

// Define the SimpleData db connection and the table for the use 
// in this controller.
var DbFile = Server.MapPath("~/App_Data/StarterSite.sdf");
var Db = Simple.Data.Database.OpenFile(DbFile);
Page.SimpleDataTable = Db.Person;

// Act on the url-action ("edit" / "insert" / "display" / "edit")
switch (action)
    case "edit":

        // Find the record in the database and store in Page.Model
        Page.Model = Page.SimpleDataTable.FindById(id);

        if (!IsPost)
            // Render the view
            @RenderPage(Page.ControllerUrl + "/_edit.cshtml");
            // Update available properties in Page Model using 
            // Request.Form data

            // Try to store data back to the database using 
            // SimpleData.Update

            // If update fails we return to the edit view with the 
            // error message from SimpleData.

            // The real user friendly validation should already be 
            // taken care of with jQuery validate,
            // this is the fallback safety validation.

            catch (Exception ex)
                Page.Message = ex.Message;
                @RenderPage(Page.ControllerUrl + "/_edit.cshtml");

The edit view

/person/_edit.cshtml is our edit view, and works just fine with just a minimal amount of code:

    <h2>Edit record</h2>   
    @if (Page.Message != "") { 
    <a href="@Page.ControllerUrl">Back to list</a>

The helpers

I created a few helper methods in App_Code/DynamicForm.cshtml to make this possible:

@helper EditorForModel()
@helper InsertForModel()
@helper DisplayForModel()
@helper DeleteForModel()
@helper TableForModel()

The helpers make use of the data in Page.Model which is handled in the controller, either a single record (for Display, Edit and Delete) or a list of records (TableForModel). I also needed a way to add Label texts, and define the editors. For that I find a dictionary with necessary metadata much easier to work with than a conventional ViewModel with data attributes.

A ViewModelDefinition

To define exactly what I like to show in the view forms I make use of a ViewModelDefinition class with which I define data fields, label texts and CssClasses in the controller, like this:

var def = new DynamicForm.ModelDefinition();
def.AddColumn("id", "hidden");
def.AddColumn("name", "Name", "text", "mandatory");
def.AddColumn("comment", "Comment", "textarea", "mandatory");
Page.ViewModelDefinition = def;    

The (preliminary) EditorForModel

In the EditorFormModel helper I use both Page.Model as well as Page.ViewModelDefinition to make the edit form.

@helper EditorForModel()
    var modelDict = (IDictionary<string, object>)Page.Model;
    <form method="post">
            @foreach (var columnDefinition in Page.ViewModelDefinition.Columns)
                var col = columnDefinition.Value;

        string value = "";

        if (Page.Model == null)
            if (col.DefaultValue != null)
                value = col.DefaultValue.ToString();
            if (col.DataField != null && col.DataField != "" && modelDict.Keys.Contains(col.DataField))
                value = (modelDict[col.DataField] ?? "").ToString();

        switch ((string)col.Type)
            case "text":
            <label for="@col.DataField">@col.LabelText</label>
            <input type="text" id="@col.DataField" name="@col.DataField" class="@col.CssClass" value="@value"/>        

            case "textarea":
            <label for="@col.DataField">@col.LabelText</label>
            <textarea id="@col.DataField" name="@col.DataField" class="@col.CssClass">@value</textarea>

            case "hidden":
            <input type="hidden" id="@col.DataField" name="@col.DataField" value="@value"/>        

            case "submit":
            <input type="submit" value="@col.LabelText"/>


I am still some steps from having code in such a quality where I can distribute this as a open source project, but I hope I will soon, or that someone else is doing it. It’s really no much work in total here as most is already in WebMatrix, and of course SimpleData.

As I said in the beginning of this post I would love to get any feedback on this.


The MVC3-problem areas wanted to try to move away from

Data classes and Datacontext complexity. A genuine stable ORM & data layer is something one never should leave behind, but for many web applications I think SimpleData makes db-crud both good enough and as lightweight and “ceremony less” as it can be.

Handle localized (translated) texts. This is easier and more direct with a ViewModelDefinition dictionary than using DataAttributes on ViewModels.

Recompiling controllers. I have come to like the dynamic Rails/Django/Php approach to web development for the closeness and speed between editing code and seing the result. In short – without needing to recompile the full application (and resetting the sessions). By editing cshtml’s the individual files are the only ones that need recompilation and that is done in the blink of the eye.

Scaffolding views. The T4-scaffolding of views is nice and makes often 90% of the work. But the way I (and I guess many with me) work I redesign everything from data to html often in small iterations. And that for that to work good in MVC 3 I would need to edit T4 templates and regenerate views for each iteration. I like the MVC3 templating (EditorFor) better, but not as much as doing everything in a Razor helper where I have great control with the best syntax available imho.

Razor helpers reduce the use of “magic”. Make the helpers your own, change the code therein just like you want and make individual versions for different controllers – when you need.

I polish the helpers easily and the polish shines through to every part of the program where the global helpers are used. (If I need individual behaviour in a view that is easy to do just by copying the global helper and editing it in the particular view).


I do need testing in my WebMatrix projects. That is something I have to explore further. Any good ideas to share?

Follow up on the dynamicforms

I made a new approach to the dynamic forms in my HtmlFormHelper.

About these ads

17 thoughts on “WebMatrix MVC-ishness with Simple.Data and FormHelpers for CRUD

  1. Wow, I was just working on the same type of Mvc-Light approach to WebMatrix/WebPages. I’ve even done some work on making/faking restful-style routes using IIS UrlRewrite Module so that you can get ruby-style restful URLs like /categories/1/posts/1/comments.

    I’m planning on maybe putting this into a simple NuGet package as a SimpleMvc framework for use with WebMatrix/WebPages.

    I plan on doing a post on it soon and maybe we could collaborate on the effort.

  2. hrjk

    Hey Jonas, very impressed with this post.

    Question, where will this code set will go?
    var def = new DynamicForm.ModelDefinition();

    And also in person.cshtml from where this code comes from:

    Am I missing anything.


  3. carelive

    Another good post. Agree with all the MVC pain points mentioned. Have been bouncing back and fourth between the two technologies. Seems like its easier to develop the project in WebMatrix then port it to MVC later……

  4. I really like your blog.. very nice colors & theme.
    Did you design this website yourself or did you hire
    someone to do it for you? Plz reply as I’m looking to design my
    own blog and would like to find out where u got
    this from. thank you

  5. kingston brass product reviews

    What’s up friends, good paragraph and good urging commented at
    this place, I am truly enjoying by these.

  6. I have been browsing online more than three hours today, yet
    I never found any interesting article like yours.

    It’s pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the internet will
    be a lot more useful than ever before.|
    I couldn’t resist commenting. Very well written!|
    I’ll right away seize your rss as I can’t to find your email subscription hyperlink or e-newsletter service.
    Do you’ve any? Please allow me recognize so that I could subscribe.
    It is appropriate time to make some plans for the future and it’s
    time to be happy. I have read this post and if I could I desire to suggest you some interesting things or advice.
    Perhaps you could write next articles referring to this article.
    I want to read even more things about it!|
    It is the best time to make a few plans for the long run and it is time to be happy.

    I have learn this put up and if I may I desire to recommend you some
    interesting things or tips. Perhaps you could write next articles referring to this article.
    I want to learn more things about it!|
    I’ve been browsing on-line greater than 3 hours lately, but I never discovered any interesting article like
    yours. It is lovely worth enough for me. Personally, if all web owners and
    bloggers made just right content as you probably did,
    the net shall be a lot more useful than ever before.|
    Ahaa, its fastidious conversation on the topic of this article
    at this place at this blog, I have read all that,
    so now me also commenting at this place.|
    I am sure this article has touched all the internet viewers, its really
    really fastidious paragraph on building up new weblog.|
    Wow, this paragraph is nice, my younger sister is analyzing
    these kinds of things, thus I am going to inform her.|
    bookmarked!!, I love your site!|
    Way cool! Some extremely valid points! I appreciate you penning this write-up plus the rest of the site is very good.|
    Hi, I do think this is an excellent web site. I stumbledupon it ;
    ) I will come back yet again since I saved as a favorite it.
    Money and freedom is the greatest way to change,
    may you be rich and continue to guide other people.|
    Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s difficult to
    get that “perfect balance” between user friendliness and
    appearance. I must say that you’ve done a awesome job with this.
    Additionally, the blog loads super fast for me on Chrome.
    Exceptional Blog!|
    These are actually impressive ideas in concerning
    blogging. You have touched some pleasant factors here.

    Any way keep up wrinting.|
    I like what you guys are up too. Such clever work and coverage!
    Keep up the awesome works guys I’ve added
    you guys to my own blogroll.|
    Hello! Someone in my Facebook group shared this website
    with us so I came to give it a look. I’m definitely enjoying the
    information. I’m book-marking and will be tweeting this to my followers!

    Outstanding blog and terrific design.|
    I really like what you guys tend to be up too. This sort
    of clever work and coverage! Keep up the
    excellent works guys I’ve incorporated you guys to my blogroll.|
    Hi would you mind stating which blog platform you’re working
    with? I’m looking to start my own blog soon but
    I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique.
    P.S Sorry for getting off-topic but I had to ask!|
    Hi there would you mind letting me know which hosting
    company you’re utilizing? I’ve loaded your blog in
    3 different browsers and I must say this blog loads a lot quicker
    then most. Can you suggest a good internet hosting provider at a
    reasonable price? Cheers, I appreciate it!|
    I love it when individuals come together and share ideas.
    Great blog, stick with it!|
    Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you! By the way, how could we communicate?|
    Hey just wanted to give you a quick heads up. The text in
    your content seem to be running off the screen in Chrome.

    I’m not sure if this is a formatting issue or something to do
    with web browser compatibility but I figured I’d post
    to let you know. The style and design look great though!

    Hope you get the problem solved soon. Kudos|
    This is a topic that is near to my heart…
    Thank you! Exactly where are your contact details though?|
    It’s very straightforward to find out any topic on web as compared to textbooks, as I found this piece of
    writing at this website.|
    Does your website have a contact page? I’m having problems locating it but,
    I’d like to send you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing.
    Either way, great website and I look forward to seeing it expand over time.|
    Hola! I’ve been reading your weblog for a long time now and finally
    got the courage to go ahead and give you a shout out from New Caney Texas!
    Just wanted to tell you keep up the good job!|
    Greetings from Ohio! I’m bored at work so I decided to
    browse your blog on my iphone during lunch break.
    I enjoy the info you provide here and can’t wait
    to take a look when I get home. I’m surprised at how quick
    your blog loaded on my mobile .. I’m not even using WIFI, just 3G
    .. Anyways, wonderful blog!|
    Its such as you read my thoughts! You seem to grasp a lot approximately this, such as you wrote the
    guide in it or something. I think that you could do with some % to pressure the message home a bit, however instead of that, that is wonderful blog.

    An excellent read. I will definitely be back.|
    I visited multiple sites except the audio feature
    for audio songs existing at this web page is in fact superb.|
    Hi, i read your blog from time to time and i own a similar
    one and i was just curious if you get a lot of spam comments?
    If so how do you stop it, any plugin or anything you
    can suggest? I get so much lately it’s driving me insane so any help is very
    much appreciated.|
    Greetings! Very useful advice within this post!

    It’s the little changes which will make the largest changes.
    Many thanks for sharing!|
    I absolutely love your site.. Very nice colors & theme.
    Did you build this web site yourself? Please reply back
    as I’m attempting to create my very own site
    and want to learn where you got this from or just what the
    theme is named. Thank you!|
    Hello there! This post could not be written much better!
    Looking at this article reminds me of my previous roommate!
    He constantly kept preaching about this. I most certainly will forward this article to him.
    Fairly certain he’s going to have a good read. Many thanks for sharing!|
    Incredible! This blog looks exactly like my old one!

    It’s on a entirely different subject but it has pretty much the
    same page layout and design. Superb choice of colors!|
    There is definately a great deal to know about this issue.
    I like all the points you’ve made.|
    You’ve made some really good points there. I checked on the
    web for more information about the issue and found most people will go
    along with your views on this web site.|
    Hi, I log on to your new stuff daily. Your story-telling style is witty, keep it up!|
    I simply couldn’t go away your website prior to suggesting that I
    really enjoyed the standard info an individual supply on your guests?
    Is gonna be back regularly in order to check out new posts|
    I wanted to thank you for this excellent read!! I definitely enjoyed every little bit of it.
    I’ve got you bookmarked to look at new stuff you post…|
    Hello, just wanted to say, I liked this post.
    It was practical. Keep on posting!|
    I drop a leave a response each time I appreciate a article on a site
    or I have something to valuable to contribute
    to the discussion. It’s triggered by the fire communicated in
    the post I browsed. And on this article WebMatrix MVC-ishness with Simple.Data and FormHelpers for CRUD
    | Coding in the cloud. I was actually moved enough to drop a leave a responsea response :
    -) I do have 2 questions for you if it’s allright. Could it be simply me or do a few of the comments come across as if they are coming from brain dead
    folks? :-P And, if you are writing at additional social sites, I would like to keep up with you.

    Would you make a list the complete urls of all your social sites like your Facebook page, twitter feed, or linkedin profile?|
    Hi there, I enjoy reading through your post.
    I like to write a little comment to support
    I every time spent my half an hour to read this web site’s content all the time along with a cup of coffee.|
    I every time emailed this webpage post page to all my contacts, since if like
    to read it next my links will too.|
    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong
    none the less. I’ve been using WordPress on numerous websites for
    about a year and am concerned about switching to another platform.
    I have heard excellent things about blogengine.net.
    Is there a way I can transfer all my wordpress content
    into it? Any kind of help would be really appreciated!|
    Hi there! I could have sworn I’ve been to your blog before but after
    looking at many of the articles I realized it’s new to me. Anyhow, I’m certainly delighted I stumbled upon it and I’ll be bookmarking it and checking back regularly!|
    Terrific work! This is the type of info that should be shared around the net.
    Shame on Google for now not positioning this submit upper!
    Come on over and consult with my website . Thank you =)|
    Heya i am for the first time here. I came across this board and I find It really
    useful & it helped me out a lot. I hope to give something back and help others like you helped me.|
    Hi there, There’s no doubt that your blog may be having web browser compatibility problems.
    Whenever I look at your website in Safari, it looks fine however when opening in Internet Explorer,
    it has some overlapping issues. I merely wanted to give you a quick heads up!

    Other than that, great website!|
    Someone essentially help to make seriously posts I’d state.
    This is the first time I frequented your website page and up to now?
    I amazed with the research you made to make this particular post incredible.
    Great task!|
    Heya i’m for the first time here. I came across this board
    and I in finding It truly helpful & it helped me out much.
    I hope to provide one thing back and help others like you
    aided me.|
    Good day! I just want to give you a huge thumbs up for the excellent info you have got here on this post.

    I’ll be returning to your website for more soon.|
    I always used to study paragraph in news papers
    but now as I am a user of internet thus from now I am using net for content,
    thanks to web.|
    Your means of explaining everything in this article is really
    nice, every one be able to easily know it, Thanks a lot.|
    Hi there, I found your website by means of Google while looking for a similar matter, your web site
    came up, it seems to be good. I have bookmarked it in my google
    Hi there, simply become alert to your blog through Google, and found that it is really informative.
    I’m going to be careful for brussels. I’ll appreciate in the event you proceed this
    in future. Lots of other folks will probably be benefited out
    of your writing. Cheers!|
    I am curious to find out what blog platform you happen to be
    utilizing? I’m having some minor security issues with my latest site and
    I would like to find something more safeguarded. Do you have any suggestions?|
    I’m really impressed with your writing skills and also
    with the layout on your blog. Is this a paid theme or
    did you modify it yourself? Either way keep up the
    excellent quality writing, it’s rare to see a nice blog like this one today.|
    I’m really impressed along with your writing skills as smartly as with the structure to your
    weblog. Is this a paid subject matter or did you customize it yourself?
    Either way keep up the nice high quality writing, it is uncommon to look a great blog like
    this one these days..|
    Hello, Neat post. There’s a problem together with your
    site in internet explorer, may test this? IE nonetheless is the
    marketplace leader and a good component of
    folks will omit your excellent writing because of this problem.|
    I am not sure where you are getting your info, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for wonderful info I was looking for
    this info for my mission.|
    Hi, i think that i saw you visited my web site so i came to “return the favor”.I am trying to find things
    to enhance my web site!I suppose its ok to use {some of|a \

  7. Have you ever considered writing an ebook or guest authoring
    on other websites? I have a blog based upon on the same information you discuss and would really
    like to have you share some stories/information. I know my
    subscribers would value your work. If you are even remotely interested,
    feel free to shoot me an email.

Leave a Reply

Fill in your details below or click an icon to log in:

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