Showing posts with label asp.net mvc. Show all posts
Showing posts with label asp.net mvc. Show all posts

Monday, April 7, 2014

Dynamic forms - with a keep it simple approach

Wouldn't it be cool if editors just could drag-and-drop input fields and rearrange the design of forms in EPiServer? I can almost hear you say: XForms. Yes, I've heard about it. I have written a fair amount of code using the good ol' built in EPiServer feature. I have even succeeded in taming the XForm Beast to obey the simple rules of MVC (with help from you great bloggers out there). But that is a different story.

What about the forms that need other features than the ones provided by EPiServer XForms?

An example scenario:
We want to collect user input by using a web based form. The input data should be passed on to a back end system for processing, and should not be stored in the EPiServer database at all. Additionally, the editors want to create different campaign pages with different forms. The editors want to A/B test the campaign pages - to learn how to reshape and adjust the form to maximize conversion rates. Can this be done with EPiServer?

Here's a simple solution: blocks.
(check out the full example at GitHub)

The Input Block
Let's write a block type that can be used in forms all over the site. Instances of the block type will behave in different ways, when used in different contexts. To succeed with that, each instance of the block type need to have really good answers to some existential questions:

What am I?

Where do I belong?

How should I act in public?

The answers come in the form of categories. It doesn't have to be like that, It's just me. I think categories are cool. They remind me of twitter hash tags (I think twitter hash tags are cool too).


What am I? (Field) Where do I belong? (Group) How should I act? (Behaviour)


This instance is a "first name" input field, existing in a "user" context,
with user input set to required.


The View
Now we have the answers to the deep questions asked earlier and can write the user interface. 


The example code has some convenience methods, 
such as generating the input field name based on the categories.


Html output generated with data from the model (the block type).
A server side regular expression pattern is also passed on to the client.


The Validation
What about validation? Dynamic forms are by nature quite unpredictable. But we know about the behaviour of the individual block, and can use that knowledge to write both custom client and server validation. In this example I am using the Zurb Foundation Abide framework to perform client script validation. 


Custom validator added to the Abide framework, 
specialized in validating first name input fields. 
The name of the validator is the value of the selected subcategory for "Field".

"David" is valid. Nice to know.


This example code has two types of server validation. First up is the data annotations defined in the model. Secondly (if necessary) there is also the ability to perform custom validation. What validator to use is determined by the block behaviour (the categories), just like selecting the client validator. Here is where specialized validation takes place, such as dependencies between individual fields in the posted form.



Form data posted to the controller action method.


Going through each item in the page content area,
find the appropriate validator and execute the validation method. 
The model is passed to the validator.


That's it.

Check out the example code at GitHub. To get up and running you need to create an EPiServer 7.5 database and (of course) configure the connectionstrings file.

I really want your feedback on this. 

Please post your comments here or contact me on Twitter.

Sunday, March 9, 2014

You might not need JavaScript

Are you about to code some awesome web stuff and have JavaScript enabled in your browser?

Turn that sh*t off!!!

Okay. Easy now.

I really like JavaScript. I like it even more than I like C#. There, I said it. And I mean it.

JavaScript is cool. JavaScript is freedom. Freedom from static typing, classes and compilation. Just code, save & browse. JavaScript is the language that help us deliver great things for the web. But what would happen if you would turn scripting off in the browser?

Oops. Dude, I can't do a thing on this web site.

Before we try to write the great things, I think we should begin to write stuff that just works. Focus on functionality. The features. Write code with quality built in from the start and without scripting dependencies. How about calling it NoScript First?

NoScript First is a development style, just like Test Driven Development and Mobile First.

Based on code I've read and written over the years I think far too many of us (myself included) misses things that really need to be there on the server: stuff like validation, security, unit tests and limiting allowed http methods. How come?

I think it is because we are humans (yes, coders are humans too). We like shortcuts. When a shortcut appear, we take it. Some shortcuts are great, some are not. Doing client script form validation, and not really testing if the server does the correct job is one of the really bad ones.

Enough.

Here's an example: a web page with user input to be sent, by posting a form to the server.

Turn JavaScript off and write the html (the view).


@using (Html.BeginForm("Add", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(model => model.Name)
    <input id="my-button" type="submit" value="Send"/>
}


Write the server code (the controller and the model). Make sure the user input is sanitized. Require an anti forgery token and limit the request to allow POST only.


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Person person)
{.....}

public class Person
{
    [MyRequiredAttributeThatSanitizesStrings]
    public string Name { get; set; }
}


Try it, test it. Maybe even unit test it?
Turn JavaScript back on, hijack the submit event and do the great things.


$('#my-button').on('click', function (clickEvent) {
    clickEvent.preventDefault();
    // do the magic here
});


When you are done, try switching between JavaScript turned on and off. Do both ways work? Remember, keep it simple. NoScript First goes very well together with Test Driven Development, by the way.

Here is a full example asp.net mvc NoScript First project:
https://github.com/DavidVujic/blog/tree/master/NoScriptFirst


ps.
Check out some of my posts and videos on test driven development:
From the streets of test driven development: JavaScript
aspConf 2012 - Quick start: test driven development
ds.

Saturday, June 15, 2013

Hipster or neckbeard?

Man, that (asp.net) webforms thing really suck, doesnt it? We should convert all our sites to mvc. For all the new stuff we’re about to develop, there is only one way: mvc. But wait a minute. I forgot to ask.

Why?

If you are developing stuff for the EPiServer CMS product, choosing between the two is a big thing these days. I think many EPiServer developers has felt left behind (myself included), being stuck with webforms when the rest of the world writes cool and awesome stuff with mvc and the frameworks that comes with it. I guess those poor SharePoint guys feel the same, dont you think?

The times are different now. All of us can be cool these days (well, almost all of us. SharePoint will get there too some day).

Ok, so it’s about being cool?

Maybe. I would choose mvc because of one thing only: test driven development (tdd). Mvc is designed for that. Webforms isn’t. The rest is just style and preferences: design patterns, view engines, frameworks.

Is test driven development cool?

I think tdd is a great tool for helping you create both short term and long term value. The result will most likely be a product with nice and simple code. Nice & simple, as in easy to understand, maintain and refactor. Test driven development with webforms is mostly depressing. But hey, that is a different blog post.

Writing testable code, huh?

Well, Im not really talking about just writing testable code. Dont do that. Do test it & the code will follow. That's doing it the test driven way.

So who is the cool guy then, webforms or mvc?

I don’t know if anything used together with .NET and Visual Studio can be considered cool, really. We should probably check with @hipsterhacker or @neckbeardhacker about that. But don’t just settle with writing testable code with asp.net mvc. Without unit tests that proves it, the code base won’t probably be testable anyway.

So, without unit tests all that is left is choosing by style and preferences. Think about if that generates any value. Then make your decision on which way to go.



ps.
Check out my recent posts and videos on test driven development:
ds.