Link here

Link here

Client-side MVC with jMVC and ASP.NET MVC

JSON, MVC, jMVC 3 Comments »

As you might expect, it’s pretty neat and simple to use jMVC with the new ASP.NET MVC framework. Since MVC coders already understand the core concept, and since I’m about to give you a handy helper assembly, it hardly takes any effort at all.

Download helper assembly | Download demo project | Browse source repository

A reminder

In case you’ve missed my other posts about jMVC, it’s a teeny-tiny Javascript library which brings the MVC coding experience into the browser. It doesn’t solve world hunger, but it does make it far easier to build UIs that change dynamically according to data entered or options chosen, without needing any calls to the server (that means you, AJAX). There’s a demo site and a tutorial on CodeProject.com, both based around the ASP.NET flavour.

If you want to use it with ASP.NET, or with Castle MonoRail, you can have the convenience of strongly-typed .NET objects on the server databound (in and out) to a dynamic UI on the client. This post will show how to get the same convenience when using ASP.NET MVC.

Installation

1. Start a new MVC Web Application, or open an existing one.

image

2. Download the jMVC for ASP.NET MVC package, or build it yourself from the sources. Copy the two DLLs somewhere accessible to your project, and add a reference to them.

image

3. In your web.config file, add a reference to the jMVCHelper namespace:

 image

Well done, you’re ready to go!

Usage

I’ll copy the same Task List example as used on the CodeProject.com article. We want to add to our MVC application a simple, fully client-side task list editor looking like this:

image

First, go to the controller that’s going to provide the data. If you just made a new MVC application using the default template, you can use HomeController.cs, and edit it to look like this:

public class HomeController : Controller
{
    private class Task
    {
        public string Name;
        public bool IsCompleted = false;
        public bool HasNotes = false;
        public string Notes = "";
    }
 
    [ControllerAction]
    public void Index()
    {            
        // Supply some initial data to jMVC
        // You'd normally get it from a database, 
	// rather than hard-coding it
        ViewData["tasks"] = new List<Task>() { 
            new Task { Name = "Feed fish", IsCompleted = true }, 
            new Task { Name = "Buy new digital SLR" } 
        };
 
        RenderView("Index");
    }
 
    [ControllerAction]
    public void About()
    {
        // Not really using this, but can leave it in place
        RenderView("About");
    }
}

So, we’ve defined a data structure for our Task objects, and assigned a List of them into the ViewData for the page.

Now, in the corresponding view (Index.aspx, in this case), you can insert the jMVC panel like so:

image

If you run the application now, you’ll get a weird 404 error because it’s trying to load /Views/jMVC/tasks.jmvc, but you haven’t created this yet. Create a new blank text file at that location. This isn’t a tutorial on jMVC syntax (for that, see this guide, or examine the samples), so just paste in the following:

<% if(model.tasks.length == 0) { %>
    <p>No tasks have been added.</p>
<% } else { %>
    <table border="1" cellpadding="6">
        <thead>
            <tr>
                <th align="left">Task</th>
                <th align="left">Status</th>
                <th align="left"></th>
            </tr>
        </thead>
        <% for(var i = 0; i < model.tasks.length; i++) { %>
            <tr>
                <td>
                    <span style='<%= model.tasks[i].IsCompleted ? "text-decoration:line-through" : "font-weight:bold" %>'>
                        <%= model.tasks[i].Name %>
                    </span>
                </td>
                <td>
                    <label>
                        <input type="checkbox" onclick="<%* function(i) { model.tasks[i].IsCompleted = this.checked } %>" 
                            <%= model.tasks[i].IsCompleted ? "checked" : "" %> />
                        Completed
                    </label>
                    <label>
                        <input type="checkbox" onclick="<%* function(i) { model.tasks[i].HasNotes = this.checked } %>" 
                            <%= model.tasks[i].HasNotes ? "checked" : "" %> />
                        Has notes
                    </label>      
                    <% if(model.tasks[i].HasNotes) { %>          
                        <div><textarea onchange="<%* function(i) { model.tasks[i].Notes = this.value; } %>">
                            <%= model.tasks[i].Notes %></textarea></div>
                    <% } %>
                </td>
                <td>
                    <a href="#" onclick="<%* function(i) { model.tasks.splice(i, 1); } %>"">Delete</a>
                </td>
            </li>
            </tr>
        <% } %>
    </table>
<% } %>
 
Add new task: 
<input type="text" id="NewTaskName" onkeypress="return event.keyCode != 13; /* don't submit form if ENTER is pressed */"/>
<input type="button" value="Add" onclick="<%* function() { addNewTask(model.tasks); } %>" />
 
<% 
    function addNewTask(taskList) {
        var taskName = document.getElementById("NewTaskName").value;
        if(taskName != "")
            taskList[taskList.length] = { Name : taskName, Notes : "" };
    }
%>

I know that looks intimidating, but it’s more interesting than just printing "Hello, world!". If you think about it for a minute, it’s similar syntax as you’d use in any ASP.NET MVC ViewPage, except in this case it’s going to be executed on the client, and Javascript event-handling is baked in. There are simpler examples on the demo site.

Soon I’m going to make the syntax cleaner by adding MVC-style view helper methods, so you’ll be able to write <%= Html.TextBox(…) %> etc., but for now you have to write all the HTML markup yourself.

Getting data back on the server

If you run the app now, you’ll be able to edit the task list. Whee! Isn’t that fun - no server communication at all!

Except there’s no way to post your work back to the server, so change your view to look like this:

 image

Note: you need to add a reference to the MVC Toolkit to use this syntax.

Now we’ve added a proper HTML form with submit button. This means that jMVC is going to post a JSON string representing the edited data to the server with the name "myJmvcPanel". To process that on the server, add a new action method to the controller:

[ControllerAction]
public void ReceiveData()
{
    // Retrieve the edited data
    List<Task> result = this.ReadJsonFromRequest<List<Task>>("myJmvcPanel", "tasks");
 
    // Do something useful with it, like save it to the database
    // In this case just prove we've got the updated data
    ViewData["count"] = result.Count;
    RenderView("About");
}

By the way, you’ll need to import the jMVCHelper namespace to use the ReadJsonFromRequest() helper method. Put this at the top of your controller file:

using jMVCHelper;

Hooray, we’re done. The user can add, edit and remove tasks in the browser with no client-server communication, then when they post the form, we get strongly-typed .NET objects to represent the submission.

If you couldn’t be bothered to type those things yourself, you can download the demo project I prepared earlier.

jMVC.NET: Neat Client-side MVC for ASP.NET

ASP.NET, JSON, Javascript, MVC, UI 11 Comments »

Here’s an idea I’ve been working on for a little while, and I think is now ready for others to use - a client-side MVC engine that slots into existing ASP.NET pages and makes it dead easy to make dynamic user interfaces.

By that, I mean UIs where the set of controls changes according to the data entered or selections made. Controls appear or disappear, enable or disable, highlight or animate, as the user interacts with them.

There are no postbacks, no AJAX trickery, and no having to write sophisticated Javascript event-handling code. It’s an effective application of the Model-View-Controller principle, running in the browser window.

Impatient? Start by checking out the demos

Example

imageMaybe I’m getting too carried away… let’s take a look at an example you can probably recognise.

Imagine you’re writing a blog application in which the user can enter a list of “tags” for each entry. You could ask them to enter a comma-separated list of strings in a single textbox, but that’s not very nice. It’s better to present a list of separate textboxes - but how many? Well, that isn’t determined in advance, so you’ll need to offer a variable number. Is that so hard?

In standard ASP.NET, despite the simplicity of the requirements, it is painful.

With a jMVC.NET control, it’s easy and clean - your server-side code looks like this:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       // Assign initial data to control
       TagList.Model[“tags”] = new string[] { “Javascript”, “MVC”, “Goodness” };
   }
}

protected void FinishedButton_Click(object sender, EventArgs e)
{
    // Retrieve updated data model from control
    string[] tags = (string[])TagList.Model[“tags”];
    // … now save the tags to database or whatever…
}

That’s all there is to it on the server. Assign the data to the control, then read back the results - there’s no intermediate processing or manipulating of controls.

Your code in-front looks like this:

image

… and you have a view template like this:

image

It’s very clean and direct, and you get a control tree that changes and updates right there in the browser with no server communication. Each time the user clicks “add” or “delete”, the underlying data model is updated, and the jMVC framework rebuilds the UI to match.

Installation and Usage

Installation consists of dropping the two DLLs into your /bin folder:

image

To add a control to your page, register the jMVC namespace in your ASPX file:

image

Add a MVCPanel control wherever you want it:

image

You might find it helpful to set “ShowDebugInfo” to true at first, so you can see how your .NET data model is represented in Javascript.

You need to add a view template - usually given the .jmvc extension but anything else if your web server won’t serve files with a .jmvc extension. It’s a plain text file, following the jMVC syntax described here.

Finally, assign data to the control’s “Model” property, and read it back after a postback.

Demos

Those short instructions hardly explain the full picture, so it’s best to look at the demo website. This outlines some realistic use cases and lets you see the source code.

If you have questions or feedback, please post a comment and I’ll reply as soon as I can.

Download

The demo website also has the latest download information, including information on accessing the public subversion repository.

License

jMVC.NET is provided under a MIT license, so you can use it in commercial or non-commercial projects.

Compatibility

On the server, you need to run ASP.NET 2.0 or higher. Browser compatibility is most modern browsers, certainly including IE6+ and Firefox 2+.

Rich Javascript MVC user interfaces with jMVC

JSON, Javascript, MVC, UI 5 Comments »
Update: jMVC is now integrated with ASP.NET - Check out details and demos here

So we can build clean, responsive user interfaces with the MVC design pattern using client-side XSLT. Nice. Now let’s imagine something much better.

What if we could take plain Javascript objects as our model (perhaps transferred to/from the server in JSON form), and translate them into a HTML user-interface using a clean, fast, and familiar templating language? A language as familiar as… Javascript itself?

Perhaps we could even set up a simple framework that would let us route events in the UI (such as button presses) into our own Javascript handler functions, and then after we update the model, it automatically refreshes the UI…

Introducing jMVC

It’s really simple. It’s a templating engine written in less than 100 lines of Javascript (excluding comments). jMVC provides a templating language which is actually Javascript, so you don’t have to learn any new syntax.

It uses ASP-style <% code %> syntax, like this:

Here are some items from an array:
<ul>
   <% for(var i = 0; i < model.items.length; i++) { %>
      <li><%= model.items[i].name %></li>
   <% } %>
</ul>

There are only three syntactical constructs (plus everything you can normally do in Javascript):

  • Code blocks, which you’ll use mostly for looping, or if/else constructs, like this:
<% if(model.cart.count > 0) { %>
    You have some stuff in your cart.
<% } else { %>
    You have nothing in your cart.
<% } %>
  • Evaluations, used to insert a value from your model into the UI, like this:
Hello <%= model.name %>, the time is <%= new Date() %>.
  • Closures (these are the fancy ones), used to attach Javascript code to events in the dynamically-generated user interface, like this:
<input type="button"
       value="Delete"
       onclick="<%* function(currentItem) { deleteItem(currentItem) } %>" />

Simple, eh?

Notice the last one - closures - because this is the only bit that isn’t completely obvious. While code blocks and evaluations run at template-processing time, the closures run later, for example when the user clicks a button or link. The magic <%* function() { ..code.. } %> syntax (notice the asterisk) means, “Here’s a block of code, don’t run it now, just register it to this event handler”.

They are closures because you can reference any variable from your model that’s in scope at the time. This is really helpful when your UI contains lists with buttons next to each item, as you can pass in the relevant item as a parameter to the event handler.

After your closure runs (during which you’ll probably update the model), the UI is automatically refreshed - that’s one less thing to think about.

Online demos

Just to prove it works, here are two demos. They will launch in a new window. They’re deliberately kept simple to demonstrate the method, so don’t expect fancy graphics.

Simple list-editing demo - download the source code to see how easy this is.

Recursive controls demo - this replicates the demo given for the XSLT method, but shows how jMVC is much more streamlined. Source code

Integrating with ASP.NET

… or another server-side language is pretty easy, because as you will see from the second demo, the JSON model can be kept in a hidden INPUT field or TEXTAREA so it gets posted back to the server. I haven’t explained this in more detail but it is simple, and I will do so if needed.

Download

You can download the full source code version here (~5kb).

There’s also a minified version (i.e. comments & blanks removed) here (~2kb).

At the moment there isn’t any documentation beyond this blog post, the source code, and the demos. It’s under 100 lines of code long, you can probably work it out. Nonetheless, if there is interest, I will write more documentation/tutorials.

License

You’re free to use and include this in commercial and non-commercial projects, including making your own modifications. You only have to retain the original copyright notice and link in the source code.

Note: it uses (and includes) the json.js library, placed into the public domain by json.org.

Alternatives

This is not a completely new idea. Although jMVC provides some unique benefits, there are loads of related projects and frameworks, each with their own advantages. Most are more developed than jMVC.

I like jMVC because it’s so small and simple. The main other benefits, compared to most Javascript templating systems, are:

  • no new, proprietary flow syntax to learn. It’s just Javascript.
  • an incredibly easy event handling mechanism, so you only need to think in MVC terms and the plumbing is done for you

Here are some alternatives you might like to check out:

  • TrimPath is one of the oldest. Unfortunately it has its own nonstandard syntax, but the website explains it well.
  • Helma looks feature-rich, e.g. the concept of sub-templates. Proprietary syntax again though.
  • ZParse might be the most sophisticated one, a bit complex perhaps, but a really nice website and demos.
  • ESTE is perhaps the most similar to jMVC. It also uses real Javascript syntax and keeps the whole business simple. Is this still actively maintained?
Site Meter