Coding Conundrums

Icon

Justin Obney – Learning Through Doing

ASP.Net, JSON, and Web Services

Everyone knows that web2.0 is quickly becoming the new web standard. With CSS3, HTML5, and JavaScript becoming standards rather than just options, web developers are now beginning to build web apps that many never thought they would see in the browser.

Today I want to talk a little bit about AJAX in ASP.Net. First let me say that I am an ASP.Net web developer. I learned to make web apps in ASP.Net before I even knew what most of the controls corresponding HTML tags were. So once I began trying to use AJAX in my sites/apps, the first way I began to get data was through some response.write and code-behind hacks. I would do all  my processing in the code behind, format my HTML string I wanted to return, and use a jQuery $.get call to fetch the HTML the response.write would output.

I know it was ugly, but I was learning.

As my data needs began to get bigger and bigger, I had to find a more efficient way to do this. I had looked at JSON a little, and had seen how a lot of the jQuery Plugins I used would implement JavaScript objects to affectively manipulate data. As I began looking more into this, I quickly determined this was the way I needed to send my data across the wire.

Now how?

Because I had now had much experience with ASP.Net web services, I quickly turned to the old hack it up method again. This meant making my JSON objects and arrays of objects in a code-behind of a page, and sending them across as a string. This turned out to be a very frustrating way to handle this, and again I knew there had to be a better way. Digging a little more into I learned that if you use a web service, ASP.Net will greatly simplify the process. I will explain in a little more detail.

First lets start with the web service..

Begin by creating a new ASP.Net web service (ASMX) file. Open the code behind and add the following ScriptService attribute to allow ASP.Net to know how to handle the code.

1
2
Public Class QuickLookup
Inherits System.Web.Services.WebService End Class

Then i create a simple structure to send the data back. The real beauty is here because ASP.Net will automatically create JSON objects and return them.

1
2
3
4
5
6
7
Public Structure FormData
        Public property1 As String
        Public property2 As String
        Public property3 As Double
        Public property4 As Integer
        Public earned As Double
    End Structure

Because I am using a master page and don’t want to register this script with all pages that inherit from it, I will add a reference to the script in the code-behind of this single .aspx page. By doing this, ASP.Net will automatically create a proxy class for the object that can be accessed through the pages javascript.

1
2
3
4
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sman As Web.UI.ScriptManager = ScriptManager.GetCurrent(Me)
        sman.Services.Add(New System.Web.UI.ServiceReference("PATH TO ASMX FILE"))
    End Sub

Next, add the function to the code behind of your web service file

1
2
3
4
5
6
7
8
9
10
    Public Function SearchCustomForms(ByVal FormName As String) As List(Of FormData)
        Dim searchResults As New List(Of FormData)
            Dim thisForm As New FormData
            thisForm.property1 = "Something"
            thisForm.property2  = "Something"
            thisForm.property3  = 5
            thisForm.property4  = "Something"
            searchResults.Add(thisForm)
        Return searchResults
    End Function

Then with a little jQuery magic, you can access the objects like so:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
$(function() {
        $('#btnGetForms').click(function() {
            QuickLookup.SearchCustomForms($("#txtSearch").val(),Pass, Fail, null);
        });
    });
    function Pass(result, context) {
        alert(result[0].property1);
     };
    function Fail(result, context) {
        alert('Fail - ' + result);
    };

The Pass Fail function calls are REALLY important here. ASP.Net automatically creates this, so you must implement it. The Pass is the function that will be called on a successful AJAX call, the fail.. well you get the idea. The last null value is the context.. I am still learning this, so check back later for updates. As of now i am not using this parameter but need to include it to work. Any other parameters you need to send, like the value of the textbox I am sending, add to the beginning of the function call.
Well blog world. I have some work to get back to. As always, all comments or questions are welcome.

jQuery RegEx Validation Framework

Hello all,

As I mentioned in a post a little while ago, I am making a jQuery validation framework that will allow input to automatically validate simply by putting a CSS Class on an element. It is official, version 0.1 is here!

At the current time, I have validation built in for the following types:

  1. Email    – CSS Class = “jValEmail”
  2. Phone Numbers– CSS Class = “jValPhone”
  3. Dates– CSS Class = “jValDate”
  4. Currency — CSS Class = “jValCurrency”   ** (format – ####.##) *All must contain 2 decimal places
  5. Numeric– CSS Class = “jValNumeric”
  6. Not Null– CSS Class = “jValRequired”

The idea is to add validation like so:

ValidationTestHTML

Then to innitiate the validation all you will do is add a click handler to the control causing the submit. like so:

Click Handler

Click Handler

As you might notice, there are some things going on with some other  CSS Classes there. While i was buying tickets to Stack Overflow Dev Days yesterday, I entered some incorrect information on the form and really liked the CSS they put on invalid information.

GoodAlertVal

So I decided I would like to do something like this and picked the following as CSS:

ValidationCSSThe idea behind “invalidGroup” is that if a control does not validate, you change the groups CSS to draw the eye to the area. Then you would use the “invalidField” to draw attention to the control inside the group. All in all it works pretty nice.

This function runs validation methods on each control with its perpective CSS Class. All validation functions are the same with the exception of the Regex they validate with and the error message they put as a tool tip.

Getting all the controls to validate

Getting all the controls to validate

Here is an example of the Currency Validation Method:

ValidationMethod

As you can see, if a field is invalid, it searches out through all its parents until it finds one with the class “blockSeperator” (which should probably be changed but It was what I used testing last night) and then adds the CSS Class “invalidGroup” to that element.

To recap, The steps are:

  1. Add CSS Classes to all inputs needing validation
  2. Add jQuery Click handler to submit button
  3. make sure Validation.js is linked
  4. Make sure CSS Classes such as “invalidField” and “invalidGroup” are linked

Well thanks for you time code world.

A working demo can be viewed here

The jQuery file can be viewed here

Found a Couple New Widgets

robots_programmer_psychiatrist_285645While I was surfing the net last night trying to fight off some sleep I desperately needed, I came across a couple new widgets I like.

The first was “ChipIn.” This is a pretty cool widget for fundraising. It allows you quickly setup a pay-pal fundraiser complete with a title, description, deadline date, and progress bar that shows how your campaign is going. It takes only a few seconds, and gives you a nice flash object to insert. Having found that, I decide that I would pop one one a couple of my sites to see if I can raise a little money for going back to school.

Secondly, I ran across the new flash widget Twitter is offering. I was very excited to see that Twitter was finally offering a flash widget for their service. I have played around with a couple of the others out there and I like this one so much better. At first, I tried to implement a straight javascript Twidget (hrrmmm.. I like the sound of that.. LOL) and it was OK. Then once I found my new best friend, jQuery, I quickly began to try to move to juitter. But I must say the one offered by twitter takes first prize. Not only does it look GREAT, it can be set up in about 3 button clicks.

I am sure that these two widgets will begin to get alot more use in my up-coming projects.

Now all I need to do is find a partner. As I look at the road ahead, I see alot of opportunity. I would greatly love to find another web-dev just coming up like myself to partner with. It is nice to have complete control sometimes, but I think the benifits will greatly out-weight the draw-backs.

Well I’m out blog world.

Donations Accepted Here

Bookmarks

Buy Me Something

Proven Portals: Best Practices for Planning, Designing, and Developing Enterprise Portals
Proven Portals: Best Practices for Planning, Designing, and Developing Enterprise Portals