Archive for the ‘Ajax’ category

Knockout – quick asp.net mvc sample

July 5th, 2010

Steve Sanderson has released knockout  – read more here about what knockout is.

Knockout is a JavaScript library that makes it easier to create rich, desktop-like user interfaces with JavaScript and HTML, using observers to make your UI automatically stay in sync with an underlying data model. It works particularly well with the MVVM pattern, offering declarative bindings somewhat like Silverlight but without the browser plugin.

Well, as a fan of his asp.net mvc book (Pro ASP.NET MVC Framework (mvc1) and just recent release of Pro ASP.NET MVC 2 – and please note – knockout isn’t at all associated or tied to asp.net mvc!) – I was quickly wanting to take his editor sample – which was so elegantly put together – and simple show a way to pass json data from a controller action to his sample.

Here is the sample code.

I’m not going to go too much into knockout – simply because Steve’s post and sample page describe it very well.  I do think this is a good follow up to a post a made regarding jTemplates. 

Enjoy!

ASP.NET MVC with JTemplates – Part II

May 20th, 2010

In my first part I of this two part series, I covered using Json, ASP.NET MVC, and jTemplate to bind to a simple html table.

The next part of this series is to ‘prettify’ the table using the jQuery plugin  DataTables

DataTables supports using the same theme as used by jQuery UI, so I have decided to include this as well.  Basically in about 4 lines of javascript, we can convert the previous simple table to a nice looking pageable, sortable, searchable grid!

image

The references are updated (see sample code):

    <link href="<%= Url.Content("~/Content/Site.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/jquery-ui-1.8.1.custom.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/demo_table_jui.css") %>" 
      rel="stylesheet"  type="text/css" />
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-ui.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-jtemplates_uncompressed.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery.dataTables.js") %>"></script>

The next step is to apply the DataTables plugin to our table.

(If you had the demo code for part I, you might notice part II I had to make sure to define the thead and tbody tags in the table.)

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type:"POST",
            url: "<%= Url.Action("GetData") %>",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                $("#jTemplateDemo").processTemplate(data);

                $('#personTable').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "aoColumns": [{ "sTitle": "First Name" },
                       { "sTitle": "Email" }]
                });
            }
        });
    });
</script>

I have included the previous javascript – the key section is the $(‘#personTable’).dataTable.

There are tons more functionality you can get from the plugin – including grid editing, server pagination, etc…  (ie. saving state – (“bStateSave”:true)

I hope to create a third part of this series that will combine the edit features of the datatable with the ASP.NET MVC + json capability.  This will be valuable to show the posting of json data as well as updating the underlying json data source for the template.

(by the way, there is an unintended “easter egg” in this post.  If you recall the template grid TH was incorrectly labeled ‘Last Name’ instead of ‘Email’. By defining the aoColumns above, it overrides the ‘Last Name’ in the template and applies the ‘Email’ header.  aoColumns is an optional parameter in this case).

I have included this code for your review – download here

ASP.NET MVC with jTemplates – Part I

May 20th, 2010

One of my goals in web development is to continue to look to use json to transmit data vs. using partial views.  Obviously by transmitting json data, the payload is going to be much more efficient.

I’m going to break this out into two parts :

Part I is going to cover the basics to using jTemplate with jQuery within an asp.net mvc environment.

Part II is going to take this concept and apply it to a nice looking jQuery plugin ‘grid control’ called  DataTables

Let’s look at what the final result will be:

image

Let’s address the server side pieces first:

I’m going to create a new Model class ‘Person’:

public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }

Using the default asp.net mvc created project type, I’ll just a hook into the the Home controller to display the table in the index page.  To do this, I’ll need to add another action with some sample data that will be called from the page via ajax:

 

 [HttpPost]
 public JsonResult GetData()
 {
      IList<Person> people = new List<Person>
        {
          new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com"},
          new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com"},
          new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com"},
          new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com"},
          new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com"}
        };
      return Json(people);
}

The ‘return Json(people)’ will return the list in json format – which you can see in the above Firebug screenshot ‘response’. 

So that is basically it for the server side.

The first step in the views is to add the references to the javascript files.  Since I’m using the site.master I’ll add it there, so that it’s available to other views as well:

image 

(For production, you will want to use the compressed/min files instead)

I also add a new ContentPlaceHolder in the head of the site.master:

<asp:ContentPlaceHolder ID="HeadContent" runat="server" />

This way on the views, I can put any scripts in the head tags as well.

In the Index.aspx page we can finish this functionality:

1. add the scripts to the head of the view:

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
        $.ajax({
                type:"POST",
                url: "<%= Url.Action("GetData") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                    $("#jTemplateDemo").processTemplate(data);
                }
            });
        });
    </script>
</asp:Content>

To review this (we could use a $.getJSON as well) – on the page ready function I’m going to make an ajax call back to the ‘GetData’ action.  This is defined in the ‘url:’ parameter.

In this case there are no parameters being passed so the data is left blank (this is best practice to include “{}” when blank).  It is possible to use a REST url as well with parameters.

We define out contentType (using $.getJSON) would do this automatically.

Lastly, we provide an ‘onSuccess’ function – the ‘data’ will contain the returning Json from our action call.  The next two calls use the jTemplate API to merge the Json data to the templated html, as shown below.

2. add the template to the view:

<script type="text/html" id="templateHolder">
    <table border="1">
    <tr>
        <th>
            First Name
        </th>
        <th>
            Email
        </th>
    </tr>
    {#foreach $T as record}
        <tr>
            <td>
                {$T.record.FirstName}
            </td>
            <td>
                {$T.record.Email}
            </td>
        </tr>
    {#/for}
</table>
</script>

<div id="jTemplateDemo">
</div>

 

One thing to keep in mind is to put this html in the script tag.  Alternatively you could load this template from another file as well.

With this approach we have created a very lightweight approach to passing data from the server to the client – the binding to the template occurs on the client.  If we used partial views, the binding process would occur on the server and transmit the payload with the html, increasing it’s size.  The lightweight json approach is critical especially in our ajax calls

Next post we’ll take this table and convert it into a ‘DataTable’.

I have included this code for your review – download here

Fantastic Friday – Links, thoughts and more…!

December 4th, 2009

Happy Friday to you  :)   I’m looking forward to my employer’s (Strategic Data Systems) Christmas party tommorow night.  It’s always a fun time.

SquareUp by Twitter

http://squareup.com/
Twitter founder formally unveils ‘Square’ project  – this is pretty cool I think – the ability to have “mobile-payments”.  

Here is a description:

The Square hardware is a small, inexpensive card reader that plugs into the audio jack of a compatible device, including a mobile phone (it’s starting with the iPhone and currently has job postings up for BlackBerry and Android engineers). It processes credit card payments, geotags their locations on a map, and e-mails a receipt to the buyer.

I think it’s a great idea – pretty cool stuff. 

Visual NHibernate Beta

At first I thought this might be ‘free’  :)   But it’s not.  However, I must say, it’s looking very nice.  Based on some NH google lists the developer(s) are very responsive to adding features and bug fixes.  That was good to see.  One of the ‘complaints’ that I hear sometimes about NHibernate (vs. like EF, L2S, or commercial ORMs) is that it’s complex to get up and running if your not familiar with how mapping files, etc… work.   So Visual NHibernate provides a visual designer and mapping tool for creating and editing NHibernate projects.

Ryan Cromwell – Castle Windsor

Not sure if I blogged on this before (yeah… I know I can search…) but I really like working with Castle Windsor’s Inversion of control container.  Ryan Cromwell (fellow contractor at Strategic Data Systems) provides a couple of good blog posts on it’s usage.  I was recently asked about factory facility for Windsor, and I was able to refer that person to Ryan’s post (see ‘Injecting WCF Channel as Dependency..’ below)

Strategy Pattern with Castle Windsor (he includes a sample project – thanks Ryan!)

Registering WPF “Views” with Windsor Fluent API

Injecting a WCF Channel as Dependency via Windsor – this shows off the Factory facility for Windsor.

By the way – a plug for Ryan:  He is our TFS specialist and can help setup, provide guidance, etc… for TFS.  If your looking for someone to do that for you – he is definitely the man to get!  I should add, he is a heck of a WPF programmer as well – he does some really fine work!

MVC Turbine – Plugin for ASP.NET MVC

http://mvcturbine.codeplex.com/

From CodePlex:

MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.

This is very good to see from my perspective.  One of the features I really enjoyed while experimenting with Grails was how easy it was to have everything injected under the covers without needing to get into the weeds (in Grails case – Spring).  MVC Turbine offers this same functionality for the ASP.NET MVC programming.

Turbine is not exclusive to a particular IoC container.  Here is a feature list:

Features

  • Visual Studio 2008 Solution Templates for IoCs
    • Ninject
    • Castle Windsor
    • StructureMap
    • Unity
  • New runtime framework that allows extensibility
    • Blades (components) that are auto-registered and loaded at runtime.
    • Introduced the Core Blades to setup the basic runtime of an MVC application:
      • MvcBlade — wiring for MVC related components (Controllers, View Engines, etc).
      • WebBlade — wiring for System.Web components (IHttpModule, etc.).
      • RoutingBlade — wiring for the IRouteConfigurator implementation.
    • RotorContext that works with the Blades to setup the runtime.
  • Auto-registration of View Engines (VE)
  • Auto-registratrion of MVC Filters to support constructor injection.
    • Added new InjectableFilter attribute to associate a filter to an action.
    • Added support for IActionFilter, IAuthorizationFilter, IErrorFilter and IResultFilter
  • InferredViewResult handles inferred actions and reports HTTP 404 for missing actions.
  • Works with ASP.NET MVC in Mono

 

Service Orientation Requires Data Orientation

More and more the conversations are around SOA.  This one article at InfoQ stuck out to me regarding ‘service data’

Most of today’s SOA literature and implementations concentrate on defining business aligned services and rarely discuss the role and impact enterprise data has in the context of SOA

 

How to Uninstall – or make Message Stop loading up on Windows 7?

How to uninstall/remove Messenger on Windows 7 ?    My dad just got a new computer with Windows 7.  Anytime he starts it up, it wants him to sign in to Messenger.  He doesn’t use Messenger, and doesn’t want to use Messenger. 

What I find irritating is there isn’t any ‘don’t show this on startup’ or ‘turn this off’ within the Messenger pop-up.  At best you have to go out to the internet and start looking for hacks or ways to turn this off.

Microsoft – I don’t mind if you want to promote your own chat program in your OS, but please be kind enough to make it easy to turn off for non-computer expert users. 

Caliburn SL Nav Walkthrough/Intro

I’ve blogged in the past regarding ‘Caliburn’ by Rob Eisenberg.  Just a reminder:

Designed to aid in the development of WPF and Silverlight applications, Caliburn implements a variety of UI patterns for solving real-world problems. Patterns that are enabled by the framework include MVC, MVP, Presentation Model (MVVM), Commands and Application Controller.

Rob is in the process of ‘releasing various starter kits/samples for Caliburn’.  His first sample just recently released is :

Silverlight Navigation Walkthrough

Using jQuery to Scroll Just in Time for Paging Records..like Bing

Rob Conery blogs about using jQuery to scroll down a list of records with ‘just in time scrolling’ for paging.  Pretty cool – I have seen this feature used in different application.  I suspect this will become the defacto standard in paging lists.  Check out his how to here.

TFS Offline

Quote of the day… ‘Don’t work offline’.  I’ll keep the source of that quote unnamed, but I did think it was rather funny.  I hope TFS improves it’s offline capabilities.  This is very reminiscent of Visual SourceSafe – which I really didn’t like much.  SVN, Git, etc… all have pretty good offline capabilities.   While we are at it – I do hope TFS also integrates with explorer so if you edit a file outside of studio that it picks it up.  (Maybe you can, but I haven’t seen it).

UPDATE  I’ve been corrected that TFS does provide explorer integration with the  TFS power tools.

(My only response though… I was told this has been around since 2005… seems almost 5 years later this would be an installation option for TFS for Visual Studio ?  Guess you just have ‘know’ this is available – lol)

Google Docs

I am setting up my ‘Google’ realm of Wave, Gmail, Docs, Reader, etc… so far… I’m loving it.  Just recently I received an email with Excel spreadsheet.  Opened it up in Gmail, which prompted to use Google docs !  Worked out great.  And to share that document with my wife, I didn’t have to forward that document around.  Just share it exclusively to her.  All stored up securely on the Google cloud.

I did notice in the Excel to Google Doc conversion that lookups aren’t exactly the same, so it didn’t properly convert the lookup lists.  I hope they fix that.   I really see the world approaching of using this approach more and more.   With the cloud storage, feature rich word processor, spreadsheet and slide creation capability… who needs an expensive desktop copy of Office!

Steve’s Final ‘Thoughts of the Day’ – (or rather ‘Stirring the ORM Pot in the .NET world…’)

Douglass Starnes has a series on different data model approaches with asp.net mvc, showing how to setup them up and use them.

In part II of the series he makes this comment: 

In the ASP.NET MVC space I see three ORMs being used most commonly.  By far the favorite outside of Microsoft is NHibernate.  Inside of Microsoft there are two competing offerings: LINQ to SQL and Entity Framework.

This view/perspective – is it a correct one ?  Is Microsoft competing against NHibernate OSS .NET projects created by it’s own community ?  Or is Microsoft just giving more options ?  Microsoft doesn’t need to include NHibernate in any of it’s products – too many legal traps I’m sure.  What if it didn’t create it’s own ORM and merely demo’d features using NHibernate in it’s examples ?  I’m all for competition to make products better, but in this case, is MS having 2 ORM’s that are catching up in functionality, but still lagging behind NHibernate and other .NET ORM’s in the market a wise thing ?  Is that how you see it ?  I went to use EF in a project, but because it didn’t handle an ‘append only’ with ‘hilo’ id generation – and because it wasn’t poco based – where the entities are the domain objects – it was finally deemed impossible to use.  Meanwhile, we prototyped NHibernate and were able to implement everything needed in the Legacy system.  Personally, I want to pick the best of breed, not pick something just because of ‘who’ makes it.  

I don’t want to distract from his series, but that comment seems to be a prevailing one in the .net community.   What I wonder is ‘doesn’t Microsoft understand that is how it will be perceived’ – and if so… is their position to outdo the products, or do they consider this a core piece of the .NET framework to provide ORM solutions ?

I keep pointing to jQuery and ASP.NET MVC – they provide jQuery in the project templates for ASP.NET MVC.   How does that compare to including NHibernate support – or even just promoting it without including it ? 

Personally I can think of 3 examples of where they could make a difference:

1. Provide a Linq provider just like they did for EF and L2S (yes, there are Nhibernate linq providers in work – there is a basic one available now)

2. Provide a NHibernate DomainService out of the box for RIA.NET

3. Provide support for NHibernate out of the box for ADO.NET Data Services.

All three could be extensions that are referenced but included in each release.

Craftsmanship Dilemma:

Last thought… I was told to just ‘get something done’ basically… hack it.  No tests, no real design, just get it done now.  Do you think that is ok ?  How does that compare to craftsmanship ?  I don’t think I have to craft the perfect 100% solution, but how it gets built – ie. with a test, with some design/OO principles in place – shouldn’t we push back a bit to not just create ‘junk’ ?  I am noticing this trend in many industries.  Just ‘build the car’, doesn’t have to last, we need it cheap and now to compete.  At what point does quality matter ?  How would you feel if the rollercoaster your going to ride is built with that mentality?  Or the bridge ?  Or the airplane ?  Or how about the breaks on your car?  Why isn’t software engineers able to defend their craft in these situations ?  I guess it’s all about the $$$  ?  There is ‘agile’ … then there is ‘craftsmanship’…

 

Well, that is enough for the day – everyone have a great weekend!

CodePlex Foundation : Ajax Library Project

November 18th, 2009

What is CodePlex Foundation?

logo[1] 

The CodePlex Foundation is a not-for-profit foundation created as a forum in which open source communities and the software development community can come together with the shared goal of increasing participation in open source community projects

(You can click on the image above to goto the website and learn more)

So the news of the day is that this foundation has created it’s first ‘gallery’, the ASP.NET Open Source Gallery.

What is a Gallery?

Galleries may be sponsored by a third-party organization, e.g. a commercial software company, or run by the Foundation. Galleries will rely on Foundation staff and volunteers to provide a set of support services, including administration, security, best practices and marketing.

Out of this gallery is the first project the ‘ASP.NET Ajax Library’.  This project has a wiki setup to learn more, get the source code, view some sample applications, etc…

http://www.asp.net/ajaxlibrary/

Head over to the ‘Learn’ section at http://www.asp.net/ajaxlibrary/learn.ashx it gives an overview of the capabilities of the library.

Some of the examples are interesting as they provide a ‘imperative’, ‘declarative’, and ‘jquery’ approach.

My ‘favorite’ example is the one on :

‘HOW TO Call ASP NET MVC Controller Actions’

I’ll snag a few snippets off that page in a shorter format – go read for the full instructions.

First, a controller action with model class:

public JsonResult GetCustomers()
{
    List<Customer> custs = new List<Customer>
    {
        new Customer
        {
            CustomerID = 1,
            FirstName = "John",
            LastName = "Doe",
            Age = 50
        },
        new Customer
        {
            CustomerID = 2,
            FirstName = "Jane",
            LastName = "Doe",
            Age = 47
        }
    };
    return Json(custs);
}

ASP. NET makes it easy to return data as Json out of the box as you can see above.

To then call this controller/action from the view:

<script src="../../Scripts/MicrosoftAjax/start.js" type="text/javascript"></script>
<script type="text/javascript">
    Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function() {
        var dataView = Sys.create.dataView('#CustomersTemplate',
            {
                dataProvider: "/Home/GetCustomers",
                autoFetch: true
            });
    });
</script>


There is a ‘dataview’ defined above with the #CustomerTemplate referring to a html element on the page of id ‘CustomerTemplate’

ie.

<div id="CustomersTemplate" class="sys-template">
    {{FirstName}} {{LastName}}
</div>

 

This should give you an idea, the other examples covering different topics are available, with sample code snippets and instructions on how to use the code.

I feel they have done a good job putting this together in a easy to follow manner, and the technology presented isn’t complex.

jQuery Ajax call – sending json data to an action

November 4th, 2008

 

UPDATE: Looks like I made an oversight here  :)   The Content-type is not being sent as json, which is why it works without the filter after all.

jQuery will require the additional parameter in the ajax call:

contentType: "application/json; charset=utf-8",

$.ajax({
                url: ‘/Home/Save’,
                type: ‘POST’,
                data: person,
                dataType: ‘json’,
                contentType: "application/json; charset=utf-8",
                beforeSend: function() { $("#saveStatus").html("Saving").show(); },
                success: function(result) {
                    alert(result.Result);
                    $("#saveStatus").html(result.Result).show();
                }
            });

 

It is possible to convert this InputStream using a DataContractJsonSerializer

As mentioned by Mike : http://msmvps.com/blogs/omar/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx

So, we’re going to need that filter after all  :)

I’m only going to modify it slightly, more a preference by me I guess – to use the Json.NET library

I’ll add this to ‘Part II’… coming right up

———-

Mike made a comment in one of my posts about sending json data to an action.  I was reading his blog post on it here ‘Passing JSON into an ASP.NET MVC Controller’ – very good stuff!

However, in one part of the post Mike comments that ‘if you try to pass a JSON object to MVC it falls apart’.

Well, I thought I’d dig in and try it out with our favorite friend jQuery.ajax

First let’s good at the sample with a few setup screens:

I added the following action to the HomeController:

image

In my sample you load the “form” with http://localhost/Home/Person which returns the ‘PersonView’

image

Clicking on the JsonPostSave button :

image 

will make the following ajax call:

image

There are two key elements here: (1) I’m passing the data, a ‘person’ json object,  in through the ‘data’ property of the ajax object and setting the dataType to ‘json’.   I’m expecting json back in my ‘success’ callback, which will be an object with a ‘Result’ property.

I’m also making a call to the url ‘Home/Save’ which will call the HomeController’s Save action:

image

In this sample, I call update model, which maps the 2 input elements to the Person object.

(nothing fancy, it’s my ‘model’  – looks like:

image )

I could create a Model binder here – as you see in my comments.  Another alternative is to pass them to the action as parameters as well (ie. Save(string FirstName, string LastName) – all three will work.

My ‘success’ call above is expecting a ‘result.Result’ – and I’m supplying this by using the return Json and creating an anonymous object with a property ‘Result’.

A few comments:

Let’s look at Firebug and see what is going on:

Here is my Header:

image

Key here is ‘Content-Type’ is application/json in the Response Header as well as ‘application/json’ in my Request Header.

The post data:

image

And the Response:

image

I think this shows you can send json data to a Action result without the Filter, although I do like those cool filters  :)

Here is the source code!

(update: sorry for the long load time – I need to cut back on the images!)

ASP.NET MVC Beta – Ajax

October 18th, 2008

I was noticing the asp.net mvc walkthrough has a section on the Beta1 ajax using the Microsoft ajax library.  Although I’m a big fan of jQuery, these two libraries now come with the framework and can be used together quite well.

In the walkthrough the code samples show a simple call to a controller which returns a string.  Let’s take that a step forward and show how it can return different types using the ‘ActionResult’.

First, make sure you include the scripts in your page – I suggest including them in the head of the master page – in the sample this is under Shared/Site.Master.

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>"
        type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
        type="text/javascript"></script>

 

(note: in the walkthrough, they are a bit outdated, it should now point to the Scripts folder, not the Content folder – which is what is recommended, as well as a part of the project template install)

Here is the sample – they have added this to the HomeController:

public string GetStatus()
{
    return "Status OK at " + DateTime.Now.ToLongTimeString();
}

public string UpdateForm(string textBox1)
{
    if (textBox1 != "Enter text")
    {
        return "You entered: \"" + textBox1.ToString() + "\" at " + DateTime.Now.ToLongTimeString();
    }  

    return String.Empty;
}
 

In step one of this, I’m going to go ahead and make a change – where I prefer to return an ActionResult here.

Since it’s just returning a string, we can return using ‘Content’. Here is an example:

 

image

Adding Ajax Helpers to The View

The Mvc framework comes with several new Ajax helpers, the two I’m going to use here from the walkthrough  is the Ajax.ActionLink and the Ajax.BeginForm.  There are named identical to the Html.ActionLink and Html.BeginForm (previously this was called ‘Form’ – now in Beta1 it’s BeginForm)

Let’s look at the ActionLink:

<%= Ajax.ActionLink(“Update Status”, “GetStatus”, new AjaxOptions{UpdateTargetId=”status” }) %>

By default, since the the container view is the ‘Home/Index’, it will look for the Action on the HomeController called ‘GetStatus’.  In the AjaxOptions – it is defining the target for the return of the GetStatus action. In this sample it is a span  with id of ‘status’ : <span id=”status”>No Status</span>  This can be a span, div, etc…  Since we have told ‘GetStatus’ above to return ‘Content’ – it will return a string and place the result in the span element.

I prefer the syntax for the helpers that is included in the Microsoft.  You’ll need to get this ‘futures’ assembly separately (here – you can learn more about it at the bottom of Scott Guthrie’s blog post on the beta1) and include it in the references as well as add a the following to the ‘namespace’ section of the web.config:

<add namespace=”Microsoft.Web.Mvc”/>

(personally I wish they would have just included it in the install… but you know how it is… lol)

So, for some reason they didn’t include the same syntax for the Ajax helpers as they did the Html helpers, the strongly typed ActionLink, ie. <%= Html.ActionLink<HomeController>(c => c.GetStatus(), “Update Status”)%>

This is preferred by me, hopefully they will include it, if not… well, I’ll make another post on how to build your own  :)

Let’s get back on track.

When we run the application, we will see the following:

image

Clicking ‘Update Status’ makes a call back to the Action – asynchronously:

image

What is happening is that the helper control is creating the link in the html using the asp.net ajax library, looking at the source, you’ll see the following:

<a href=”/Home/GetStatus” onclick=”Sys.Mvc.AsyncHyperlink.handleClick(this,

new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace,

updateTargetId: ‘status’ });”>Update Status</a>

 

Let’s take a brief look at the code here and how we can include some events to the Ajax.ActionLink,

the screenshot below shows the available ‘AjaxOptions’:

image 

Let’s add some functionality and handle the 2 most common events, the ‘OnBegin’ and ‘OnSuccess’:

 
image
 
 

The ‘OnBegin’ is going to handle the event fired before the actual ajax call is made, and the ‘OnSuccess’

will let us handle when the call is done (note: always handle the ‘OnFailure’ as well, in case of any errors!)

In my example I’m adding ‘OnRequest’ and ‘OnResponse’ – these are javascript functions, let’s look here:

 
image 

When the link is clicked, an alert box will open, when it’s done, you’ll get a second alert box. As you might notice I’ve included the ‘content’ in the OnResponse. Using Firebug, we can look at the object in detail:

 
image
 

We can see the xmlHttpRequest object and it’s request to the action ‘GetStatus’. I’m not going to go into more detail into the asp.net ajax library, but you can read more here

I should note, a good way to handle your own validation in javascript is to make validation calls in the ‘OnBegin’ – and if you want to stop the ajax call from continuing, you can return false.

So, let’s go ahead and show a similiar example with a Ajax.BeginForm, as with above, I’m converting the sample that returns a string, to return an ActionResult, using return Content(…):

image

In the view, I’m using the Ajax.BeginForm – (note that I’m wrapping it in a using statement, which I consider to be the best practice):

image

I’ve included handlers for the OnComplete, OnBeing, and OnFailure:

image

(I did manage to sneak in some jQuery goodness, using the $(“#textBox1″) to get the textBox1 element’s value)

Let’s make a minor adjustment here!  Let’s say I want to return some content, outside of ‘just a string’ ?  What I do on my project is have the ActionResult return a control.  Let’s set this up for our grand finale:

Step One:

Create a new Ajax.ActionLink: (you can do this with a form)

image

Step Two:

Create the action on the controller (home):

image

Step Three:

Create a ‘MVC View User Control’ (ascx):

image

image

Step Four:

Add some content to the control:

image

As I show, you can add a model to this control, etc… if you want to see that let me know.

Now, let’s run this add see what our result is:

We added the link at the bottom:

image

When it get’s clicked, it makes an asynchronous call, and then updating just the ‘status’ span (partial page update):

image

This is, imo, much more efficient and clean, then let’s say an ‘UpdatePanel’ in Webforms.  I have full control over the page.  The addition of the asp.net ajax libraries with ajax helpers really helps make this simple to use but extremely powerful.

Example available

AJAX Updates for IE 8 Beta 2

October 8th, 2008

Check out the blog post on some of the AJAX updates coming for IE 8

The AJAX updates we’ve chosen for Beta 2 focus on maintaining cross-browser compatibility and the feature sets that developers have thought would be the most useful. Without further ado, here they are.

Post Affiliate Xpress

October 5th, 2008

Check out the sample here:

http://samples.gwtphp.com/pax4/merchants/index.php

I’m quite impressed!

From Ajaxian post:

The UI combines a Vista-like “Start” menu along with an OS X-like dock (using everyone’s favorite fish-eye widget). It also has a built-in widget system that leverages Google Widgets. Overall, it’s a pretty nice implementation of a desktop and windowing in Ajax.

The framework itself is “GwtPHP” which attempts to take all the advantages of GWT and deploy them to PHP backends in an attempt to solve the problem of limited Java-friendly hosting services. Unfortunately, the framework isn’t available for use until sometime in early November.

Dual-License

The developers intend to use the familiar “free for hobbyists, pay up for commercial use” licensing model (what their licensing page calls a “what for what” model).

Give some feedback

Viktor says that they are quite keen to get feedback from folks on the project, so interested folks should get in touch, let them know what you think about the licensing model, and perhaps get early access, etc.

 

What is interesting is that with items from jQuery – like the jqmModel dialogs, menu controls, etc… it wouldn’t be a far stretch to pull this off with asp.net mvc and jQuery.

But, that aside, it’s a powerful display of the richness you can achieve.  My question to back to all of you would be ‘shouldn’t you be able to do this with Silverlight’  :)   In my opinion, this is the sort of application that Silverlight should be able to accomplish.

Multiple ‘Simultaneous’ Ajax Calls with jQuery

September 5th, 2008

One major problem with ajax is that when sending two ajax calls – there is no guarantee which call will return first – resulting in data being ‘mixed’ up.

The first time I saw this it was very confusing!

ie.

Let’s say I have two parts of a page that need to be updated –

function UpdatePage(){
     UpdatePart1();
     UpdatePart2();
}

 

function UpdatePart1(){
     $.ajax(beforeSend…, success…);
}

function UpdatePart2(){
     $.ajax(beforeSend…, success…);
}

What can occur in this situation is that the UpdatePart2 can return before the UpdatePart1 – and the ‘success’ from UpdatePart2 will being getting the ‘success’ from UpdatePart1  -definitely not good!!!

So…one way, is to only call UpdatePart2 on the success of UpdatePart1…but… not really as efficient of course.

What to do?

UPDATE:  Danger Will Robinson!  Ok, this actually works fine in Google Chrome and Firefox, but dreadfully it caused issues in IE.

So… what to do?

Check out this one instead:

http://dev.jquery.com/view/trunk/plugins/ajaxQueue/jquery.ajaxQueue.js

‘ajaxQueue’

Now, the usage is off a tad in that link, that usage is from an earlier version.  The code listed there extends the $.ajax call, which is nice, by adding in one additional setting called ‘mode’

ie.

$.ajax({
     mode: ‘queue’,
     url: “test.php”,
      success: function(html){ jQuery(“ul”).append(html); }
});

modes available are ‘queue’, ‘sync’, and ‘abort’.   For the record I’ve only used ‘queue’ and it worked great on all 3 browsers (IE 7, Chrome, FF 3)

In my code I had to loop through a list, sending out a request for each item in succession (printer queue).  This worked well for my case, ensuring no overlapping or wierd results (and boy, in IE it was all over the place with the commented out code below…)

Well,  the “AJAX Queue/Synch/Abort/Block Manager” comes to the rescue  :)

Helps you to manage AJAX requests and responses (i.e. abort requests, block requests, order responses). It is inspired by the AJAX Queue Plugin and the AjaxQueue document in the jQuery-Wiki.

This is very easy to implement and have some great features as well.

Let’s take our above sample and rewrite it using the AjaxManager:

function UpdatePage(){
    var ajaxManager1 = $.manageAjax({manageType: ‘normal’, maxReq: 0, blockSameRequest:true});
    ajaxManager1.add({
         beforeSend…success…url, etc…
    });

   ajaxManager1.add({
         beforeSend…success…url, etc…
    });
}

Easy as I said to implement – I’m taking the two calls from above, adding each .ajax call to the AjaxManager.

What really shines here are the options available: (From the link above)

  • normal jQuery-Ajax-Options
  • manageType: (string) the queue-type specifies the queue-behaviour (default: ‘normal’):
    • ‘sync’: synchronizes the incomming responses (callbacks) in the same order the requests were made
    • ‘queue’: queues your AJAX-requests (you have to set the maxReq-Option)
    • ‘abortOld’: aborts all “older” requests, if there is a response of a newer request
    • ‘normal’: normal behvaiour
  • maxReq: (number) limits the number of simultaneous request in the queue. If you don´t use ‘queue’ as your manageType, then older requests will be aborted. (default: 0 = unlimited requests)
  • blockSameRequest: (boolean) prevents same request, compares url, data and type in the same queue to determine, wether the same request is already in process. (default: false)

 

So in my sample, I’m using the normal behavior, with unlimited requests, however, I do set the blockSameRequest to ‘true’ – obviously you can configure this to meet your needs.

And…. it’s free and built with the wonderful jQuery library  :)