Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Wednesday, October 30, 2013

Divorcing the UpdatePanel for Asynchronous Postbacks in Web Forms Isn't Easy

Point MVC vs. web forms here in the effort to make ajax calls to the server for asynchronous postbacks. This experience made me realize how nice MVC is from this respect I'm about to highlight.

For years I used ASP.NET UpdatePanels in web forms development and overall they have done the job. However, anyone that has used them on mildly complex pages knows, you can't just have 1 UpdatePanel. Nope, you need 2 with the 2nd one having a trigger pointing to the 1st so partial updates will work properly. The end result: a tangled web of UpdatePanel goo.

Recently I decided to use jQuery making AJAX calls to ASP.NET page methods instead as an alternative to UpdatePanels. The jQuery in it of itself may not be 100% cleaner but it works really well and is straight forward. So I create my ASP.NET page method, write some jQuery to make a call to my new page method asynchronously, and walla I have bypassed the UpdatePanel, yeah!

Not so fast...

Caveat #1: Page Method Must Be Static. This will by the way not be ideal for anyone doing Dependency Injection as you will have to Publicly resolve dependencies through methods like: Global.GetInstance()

Caveat #2: Can't see my server side controls 
from the static method called (because of #1 above and how it's called from the client).

Caveat #3: Normal postbacks later that access or post bound clientside elements complain of security and EnableEventValidation issue.

Caveat #4: Be prepared to query element values via Request.Form and not through control instances.

End result: A worse mess than using an UpdatePanel.

Recommendation: If you are doing ASP.NET web form development here are the (3) choices I recommend:

  1. Deal with full postbacks like it's 2002
  2. Use an UpdatePanel for asynchronous postbacks and don't mix client side data binding asynchronously with JavaScript.
  3. Ditch ASP.NET web forms and do MVC (hey no hater here, I stick up for web forms a lot - just know how the tool operates)
I want to show through an example all of what I just described. So 1st, lets look at a simple example to populate a ASP.NET ListBox server control's items using an AJAX call to the server to just see how this works. We'll make a DropDownList that contains the 'Periods' during a school day. Upon selection we want to have the classes populated in the ListBox. The goal is to do this without having a full postback or use an UpdatePanel.

First a simple set of server controls:

<form id="form1" runat="server">
    <div>
       <asp:DropDownList ID="DropDownList1" runat="server">
          <asp:ListItem Text="Please Select..." Value="0"></asp:ListItem>
          <asp:ListItem Text="1st Period" Value="1"></asp:ListItem>
          <asp:ListItem Text="2nd Period" Value="2"></asp:ListItem>
       </asp:DropDownList>
    </div>
    <div>
       <asp:ListBox ID="ListBox1" runat="server" Width="400px" SelectionMode="Multiple"></asp:ListBox>
    </div>
    <div>
       <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
    <div>
       <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
    </div>  
</form>


Next we need a Static server-side event with the [WebMethod] attribute added that our jQuery we will make can make an AJAX call to and will return a collection of 'School Classes' for the 'Period' selected:
public partial class Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [WebMethod]
   public static List<SchoolClasses> DropDownList1_SelectedIndexChanged(string id)
   {
 if (id == "0")
 {
    return null;
 }

 //Generic code representing call probably to retrieve values from the database
 var classesPeriod1 = new List<SchoolClasses>()
    {
  new SchoolClasses(){ID = 1, Name = "Math 101"},
  new SchoolClasses(){ID = 2, Name = "Science 101"},
  new SchoolClasses(){ID = 3, Name = "Social Studies 101"},
  new SchoolClasses(){ID = 4, Name = "Spanish 101"}
    };
 var classesPeriod2 = new List<SchoolClasses>()
    {
  new SchoolClasses(){ID = 5, Name = "Art 101"},
  new SchoolClasses(){ID = 6, Name = "Music 101"},
  new SchoolClasses(){ID = 7, Name = "English 101"},
  new SchoolClasses(){ID = 8, Name = "Global Studies 101"}
    };

 List<SchoolClasses> results = null;
 if (id == "1")
 {
    results = classesPeriod1.ToList();
 }
 if (id == "2")
 {
    results = classesPeriod2.ToList();
 }

 //this.Label1.Text == "You selected a id = " + id;

    return results;
 }

   protected void Button1_Click(object sender, EventArgs e)
   {
      var selectedItems = this.ListBox1.Items.Cast<ListItem>().Where(li => li.Selected).ToList();
      //The collection is empty?? There were selected items though...
   }
}

public class SchoolClasses
{
   public int ID { get; set; }
   public string Name { get; set; }
}

Lastly, we need the jQuery that is wired up to the 'change' event of the DropDownList that will call our new Static event server-side and populate the ListBox with the results.
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
   <script type="text/javascript">

      $(document).ready(function () {
         DropDownList1_OnChangeHandler();
      });

      function DropDownList1_OnChangeHandler() {
         // Add the page method call as an change handler for DropDownList1.
         // This will call the static page method, and use the returned results to populate ListBox1.
         $('#<%=DropDownList1.ClientID %>').change(function () {
            var val = $(this).val();
            var text = $(this).children("option:selected").text();
            var $timePeriod = $('#<%=ListBox1.ClientID %>');
            $timePeriod.attr('disabled', 'disabled');
            $timePeriod.empty();
            $timePeriod.append('<option value="0">< Loading Please Wait... ></option>');
            $.ajax({
               type: "POST",
               url: "Default.aspx/DropDownList1_SelectedIndexChanged",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               data: "{'id':'" + val + "'}",
               success: function (schoolClasses) {
                  $timePeriod.removeAttr('disabled');
                  $timePeriod.empty();
                  if (schoolClasses.d == null) {
                     return;
                  }
                  $.each(schoolClasses.d, function (i, schoolClass) {
                     $timePeriod.append('<option value="' + schoolClass.ID + '">' + schoolClass.Name + '</option>');
                  });
               },
               error: function () {
                  $timePeriod.empty();
                  $timePeriod.append('<option value="0">< Error Loading classes ></option>');
                  alert('Failed to retrieve classes.');
               }
            });
         });

      }
   </script>


If you built this example and ran it, the ListBox would populate as we would like. In fact it's really fast too. Originally I thought, "Home Run!" So what's the problem? Well if we have a simple example this might work, but as we need to add to the page, we begin to run into hurdles.



Let's try to add in (2) more features to highlight what I'm talking about:

  1. Update a label to state which 'Period' we selected when calling server-side Static method.
  2. Iterate through the 'Selected Items' collection on submittal of the form
OK, I know what you might be thinking thus far; EASY! I've done this a million times. Well, let's dig in and look at some of the challenges I listed at the beginning of this post.

First, add this line to our Static server-side method:
this.Label1.Text == "You selected a id = " + id;

Next, add this code to the server-side button click event to iterate through the selected items.
protected void Button1_Click(object sender, EventArgs e)
{
  var selectedItems = this.ListBox1.Items.Cast<listitem>().Where(li => li.Selected).ToList();
  //The collection is empty?? There were selected items though...
}


Now try to run this code. There is already an error with trying to access the Label's .Text property. Why? See #1 and #2 in the original list of issues. In a static method on the page, I can not see or have access to the Page's instance. Makes sense actually. I making a quick call to the server, but not in the context of how ASP.NET would expect, but rather from the client. Still completely legal to have the Static method, just will not behave as we might have hoped.

Comment out the the code to change the Label's .Text property. Now run the page, select some values in the dropdown and press the 'Submit' button. This time we have another issue; a hard error stating: "Invalid postback or callback argument." Why? See #2, #3, and #4. The server did not originally send the data to populate the ListBox, so it is unaware of it. This will cause a security error unless the page's EnableEventValidation="false" property is set. However I don't like to do this because it opens up a security risk and would not be something I recommend in production applications.

However if we do set to false EnableEventValidation, then we still can't see the values from our control, because the Server did not provide them and has no knowledge of them. How do we get them? Well you could use the Request.Form values and manually dig through the posted form to scrape out the elements. At this point, I'm thinking... Yuck.

So in order to make my AJAX call work to interact with the server using asynchronous postbacks and avoiding the UpdatePanel I have to deal with the following:
  • Reduce the page's security by setting EnableEventValidation="false"
  • Not be able to see any of the control values I manipulated through their server-side properties.
  • Have to dig through Request.Form to manually find updated client values
  • Not be able to use Dependency Injection as intended
  • Have a disorganized mismatch between the client and server state since the right-hand doesn't know what the left is doing.
At this point I think, is an UpdatePanel so bad compared to all of what I just discovered? Let's review the UpdatePanel code again:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
 <asp:ListBox ID="ListBox1" runat="server" Width="300px" SelectionMode="Multiple" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" />
    </ContentTemplate>
</asp:UpdatePanel>

Nope, that actually was not so bad. So the end result for a web forms applications was I stuck with the Update Panels and everything worked well in regards to asynchronous postbacks. As I mentioned at the beginning, I think this is where MVC really shines, because there is no state being tracked and updated by the server and causing at least a portion of this mess because of the mismatch between the client updates happening independent of the server knowing about it.

Hopefully you try all of this out and see the caveats of trying to do AJAX asynchronous postbacks to the server via jQuery before going to far down the road on a new project hoping this will work smoothly. There are as I've shown several 'pitfalls' to be aware of so just make sure you factor them in if going down this route.

Wednesday, March 21, 2012

How To Handle OnChange / SelectedIndexChanged Type Event In JavaScript For The AJAX ComboBox

If you have ever used the AJAX ComboBox control and needed to interact with it client side in JavaScript, you will notice it's a bit of a different animal than it's ASP.NET server control counterpart: the DropDownList. If you want to get either the selected text or its value from a traditional DropDownList, all you needed to do was add an JavaScript function call to the 'onchange' client side property on the control like below:
<asp:DropDownList ID="AspNetDDL1" runat="server" AppendDataBoundItems="true" 
onchange="dropDownListOnChange(this);">
<asp:ListItem Text="( Select a Color )" Value="0" />
<asp:ListItem Text="Red" Value="1" />
<asp:ListItem Text="White" Value="2" />
<asp:ListItem Text="Blue" Value="3" />
</asp:DropDownList>
The JavaScript method for getting the value from an ASP.NET DropDownList is just as trivial as shown below. It will fire the alert each time a valid selection is made.
function dropDownListOnChange(sender) {
if (sender.value = 1) {
alert('You selected Red!');
}
else if (sender.value = 2) {
alert('You selected White!');
}
else if (sender.value = 3) {
alert('You selected Blue!');
}
}
However the AJAX ComboBox is a bit different and not just some user control inheriting from the ASP.NET DropDownList with all of the same properties and events. The AJAX ComboBox is built from the ground up, and when rendered to the client is comprised of (4) main parts:

- A text box showing the selected item.
- A button to press to show the list (usually a down arrow)
- An unordered list with all of the items bound.
- A hidden field with the selected value.

Now the common misconception is to try and handle client side events on the textbox or the unordered list like 'blur', 'keydown', 'keyup', 'change', or 'mousemove'. The problem is none of the events used individually or collectively (jQuery allows binding to multiple events easy) work perfectly. It requires the user to tab off the field, move the mouse, or some other action before the JS function gets called. That's not ideal at all as the selection from the ComboBox might be the only control on a page, or the last one on a page, and the client doesn't do any of the actions required. If for example the result of your wired up JS function is to show/hide other controls, then you want the JS function to fire immediately without delay and as it should.

The answer lies in some 'hard to find' documented events that can have functions assigned to handle these events. Specifically for this topic we are speaking of the add_propertyChanged event handler. We need to wire up this handler to our AJAX ComboBox client side which will then allow us to get the selected item or value client-side without having to make an expensive server trip. The documentation on the event handler is below:

Sys.Component.propertyChanged Event

As a side note, always keep this advice in mind. If you are a web developer and especially an ASP.NET webforms developer, it's all too easy to get lazy and inefficient by doing everything server-side. Why? Because you can! And how do we masquerade expensive server trips? With AJAX UpdatePanels, yeah! Don't get me wrong, I really like asynchronous postbacks with UpdatePanels and use them often, but make sure to use them when you actually need to go server side to make a call. If you make a dropdownlist, radio button, checkbox, or other server control go server side just to show another hidden row, add a control, or change some visual state, then you are bloating the time it takes to run your code and making a bad choice but not handling things that can take place 100% client side on the client. With all the JS explosion recently with libraries like jQuery there is no reason not to handle these types of needs client side.

Back on the AJAX ComboBox, we need to assign a function to the add_propertyChanged event handler on our control. Remember to get the ClientID of the value for server controls, as you cannot just pass in the raw ID.
function AJAXComboBox1_Change() {
//Add event to ui_ddlStrategicObjective AJAX Combobox:
$find('<%=AJAXComboBox1.ClientID %>').add_propertyChanged(function (sender, e) {
if (e.get_propertyName() == 'selectedIndex') {
//Gets the selected index from the HiddenField associated with the AJAX Combobox control.
var selectedIndex = sender.get_hiddenFieldControl().value;
////Gets the selected text from the AJAX ComboBox
var selectedText = sender.get_textBoxControl().value;

//Just sample JS code - you could do anything here:
//show/hide controls, alerts, change client settings, etc.
if (sender.value = 1) {
alert('You selected Red!');
}
else if (sender.value = 2) {
alert('You selected White!');
}
else if (sender.value = 3) {
alert('You selected Blue!');
}
}
});

//AJAX's pageLoad function automatically provides a handler for the 'load' event
function pageLoad() {
//Make call to handle selection changes to the 'AJAXComboBox1' AJAX Combo Box
AJAXComboBox1_Change()
}
Take notice above how we call our new function 'AJAXComboBox1_Change' in pageLoad(). You cannot interact with a control until it has been initialized (i.e. you cannot call add_propertyChanged on a control unless the control actually exists). A control does not exist until the initialization phase of the ASP.NET AJAX framework is complete. We can use AJAX's 'pageLoad()' method as this script needs to be ran during postbacks and partial postbacks is using UpdatePanels. The pageLoad function automatically provides a handler for the 'load' event. You can read about AJAX Client Events in the link below.

ASP.NET AJAX Client Life-Cycle Events

In conclusion there are a few 'big picture' points to make about this entry. First and foremost, when doing web development, try and make your applications as efficient as possible by doing operations client side that don't need to be done on the server (even if they can be done that way).

Second, the AJAX ComboBox may not be a widely used control going forward because its main draw which is the JS support for typing in values and quickly selecting them has been superseded in my opinion by things like the jQuery AutoComplete extender. Dropdowns in general are probably a good choice for the 1-25ish item range, but anything more bloats the page size. In this case making async callbacks to get values real time (like with the jQuery autocomplete) is a better idea. However, it does not mean there aren't a ton of apps already using the AJAX ComboBox, and the need to interact with it client side may present itself someday. If this 'someday' comes up (which it usually does), you will now be prepared to capture its values in JavaScript.

Friday, March 2, 2012

One Of A Thousand Possible Reasons For The "Invalid Postback or Callback Argument" Exception

The "Invalid postback or callback argument." exception in .NET can be caused by a slew of different reasons stemming from ASP.NET not being able to validate that a control event originated from the user interface that was rendered by that control. The most common solution offered as we all know is to set Page.EnableEventValidation = "False". Wrong! That's not a good idea from a security standpoint.

The better option is to determine what is causing the issue, and the bad news is debugging the code will not typically lead to the answer. You have to understand the code you have written and its relationship to this property to think about what you have done to cause this issue.

My most recent cause and solution? I made an update to a control outside the UpdatePanel housing a control that initiated the event, and 
redirected to another page from an ASP.NET menu after postback had completed. It immediately threw the "Invalid postback or callback argument" exception. The fix? Add the appropriate AsyncPostBackTrigger on the other UpdatePanel with the control being updated containing the event that is doing the updating. As soon as I did this, I was obeying all the good security rules and no need to set Page.EnableEventValidation = "False" which I never want to do as a lazy resort because I can't figure out what I did incorrectly.

Saturday, September 26, 2009

How To: Make an asynchronous call from an AJAX Modal Popup

I have been asked a few times and seen some confusion occasionally around making an asyncronous postback call from an AJAX Modal Popup. The purpose of doing this is to be able to make a server side call from the Modal Popup without having it dissapear or 'Hide', which then reverts the view back to the main page.

There is really no low level magic to making this happen, but rather it just involves making sure the proper AJAX UpdatePanels, and associated AsyncPostBackTriggers are placed in the correct locations.

I think the confusion sometime lies around where the UpdatePanel is to be located. I have seen times where the developer feels it should wrap the entire control referenced by the modalpopupextender, but actually it only needs to be placed around the individual control(s) causing the postback within the modal popup.

For this example, I made a simple page with a 'Show AJAX Modal Popup' button that displays the popup. Then a button within the modal popup calls its server side click event to change the label's 'Text' property. This is all done without the modal popup ever closing.

First, take a look at the source for the .aspx page:



<%@ Register Assembly="AjaxControlToolkit, Version=3.0.30512.20315, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
Namespace="AjaxControlToolkit" TagPrefix="AjaxControlToolkit" %>












PopupControlID="pnlTestPostback" BackgroundCssClass="modalBackground" DropShadow="true">







Second, look at the code behind:


Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnShowModalPopup_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnShowModalPopup.Click
If Page.IsValid Then
Me.ModalPopupExtender1.Show()
End If
End Sub
Private Sub btnTestPostback_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTestPostback.Click
Me.lblMessage.Text = "We made an asynchronous call server side from a modal popup."
End Sub
Private Sub btnCloseModalPopup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCloseModalPopup.Click
'Reset the text back to its default message:
Me.lblMessage.Text = "Press to test postback without full postback."
Me.ModalPopupExtender1.Hide()
End Sub
End Class


As you can see the trick was the placement of the UpdatePanel and having an AsyncPostBackTrigger in the UpdatePanel containing the label, to the '
btnTestPostback' click event. You may ask why both controls (label and button) didn't just go in the same UpdatePanel; well I was trying to show an example that could be more scalable to a larger ModalPopup with a greater number of control that could not be placed in the same UpdatePanel.


If you ever have any problems getting this implemented on a larger project, I recommend removing the UpdatePanels and associated triggers, and adding them back in carefully one at a time to get the behavior you are trying to accomplish.