Modern web pages don’t have to post back to change their presentation to the user.
There are many ways to implement these types of features and ASP.NET Web Pages with Microsoft WebMatrix is no different. 

An AJAX callable service can return results in amy different formats, JSON, POX, Encoded Binary, etc. 

In the case below we’ll implement a “service” in a .CSHTML page and it will return a snippet of HTML markup. 

The calling page looks like this.


@{
Layout = '~/_SiteLayout.cshtml';
Page.Title = 'Welcome to my Web Site!';
}

<br /><br />
<div id='TextDiv'>
    ASP.NET Web Pages make it easy to build powerful .NET 
    based applications for the web.
</div>

<p>
<input id='TextInput' type='text' />
<br /><br />
<button id='mybutton'>Make an AJAX request .... </button>
<script type='text/javascript'>
   function show(indata)
    {
    TextDiv.innerHTML = indata;
    }
</script>
<script type='text/javascript' src='xmlhttp.js'></script>
<script type='text/javascript'>
  document.getElementById('mybutton').onclick = function () {
        var d = document.getElementById('TextInput');
        doHttpRequest('Service.cshtml?' + d.value, show);
  }
</script>
</p>

You’ll note that this is a modified version of the Default.cshtml page from the default WebMatrix Starter Site Template.

Line 21 Includes a JavaScript file which contains the plumbing to make an HTTP request from our client side code.

On line 23 we wire a handler for the HTML button’s click event.

On line 24 we get a reference to the text input field where we will retrieve data to send to our service.

Then line 25 calls a JavaScript function doHttpRequest() wich is defined in xmlhttp.js

doHttpRequest(‘Service.cshtml?’ + d.value, show);

Note the two arguments.

  1. “Service.cshtml” is the endpoint to be called. In this case, a simple WebMatrix page (and a QueryString Argument)
  2. A callback function (in our case defined beginning at line 16)

Lets take a look at xmlhttp.js


function doHttpRequest(url, callback_function, return_xml)
{
  var http_request, response, i;

  var activex_ids = [
    'MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP',
    'Microsoft.XMLHTTP'
  ];

  if (window.XMLHttpRequest)
  {
    // Internet Explorer 7 or greater, Mozilla, Safari, etc.
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType)
       {
       http_request.overrideMimeType('text/xml');
       }
   }
   else if (window.ActiveXObject)
   {
    // IE6 and below
    for (i = 0; i &lt; activex_ids.length; i++)
    {
      try
      {
        http_request = new ActiveXObject(activex_ids[i]);
      }
      catch (e)
      {
      // Add error handling here.
      }
    }
  }

  if (!http_request) {
    alert('Current browser does not support http requests.');
    return false;
  }

  http_request.onreadystatechange = function()
  {
    if (http_request.readyState !== 4)
    {
        // Response not ready.
        return;
    }

    if (http_request.status !== 200)
    {
      // Repsponse ready, but not [200] OK
      alert('The request resulted in an error. 
           (Code: ' + http_request.status + ')');
      return;
    }

    if (return_xml)
    {
      response = http_request.responseXML;
    }
    else
    {
      response = http_request.responseText;
    }
    // Do Callback
    callback_function(response);
  };

  http_request.open('GET', url, true);
  http_request.send(null);
}

The bulk of the code is plumbing and error handling, making sure we can create the XmlHttpRequest object, which requres a dufferent methodology depending on which browser the code is running in.

In future demos I’ll relly on jQuery for AJAX service calls. Among other advantages, jQuery handles browser differences for us.

The service itself is a sample page I’ll name Service.cshtml

It looks like this:



@{
    var MyOutPut = "";
    if(Request.QueryString[0] != "")
    {
        MyOutPut = Request.QueryString[0] + " Data Recieved";
    }

    @MyOutPut
    @:<strong> >>>>>>> &amp;nbsp;  @DateTime.Now   </strong>
}

Note that, unlike the rest of the pages in our site, this one does NOT use a layout inclusion, nor does it specify a doc tgype, etc.

It doesn’t actually return a page at all but rather a simple, but dynamic, bit of HTML markup.

While there are many more complex ways for code in the browser with code on the server, often that complecity isn’t necessary.

This simple method will get you providing dynamic page updates to you ASP.NET WebMatrix Web Pages.

[ Download a working sample HERE ]