JayData Makes Web Phenomenal !

Leave a comment


 

Creating Single Page Application, Web API, Upshot, An Exposed Service bring your data from Json Endpoints (maybe WEB API) … all of this is the new nueva moda.

This is nice till now. But the catastrophy started when you want to map your JSON with your EF Objects. Serializing stuff! Not Serializble! What the Hell! so change return type to ‘dynamic’ and bring ‘anonymous object’ … upshot is not documented!! And the Single Page Architecture Template (which is provided by Microsoft) .. Not mature enough! So simply they removed it from VS 12.

And Finally God guide me to JayData! Its amazing and phenomenal.

That’s what happened to me when I saw the first video for JayData

Imagine, Silverlight RIA can be used in Web. This “Framework” .. not just library

Solve this things in Previous Microsoft Single Page Architecture:

  • Generating the whole EF Model + Metadata automatically using JaySvcUtil.exe (You can see this in video)
  • Do not bother your self by creating many Web API controllers and doing all that mapping stuff between C# and JavaScript.
  • Getting optimized Data (Just needed data):

7-31-2012 6-02-35 AM

In this image you can see how I’m getting the Whole users from the WCF Data Service.

map ==> Used to get a specific properties from the object (That’s will minimize the size of the requested data; which means some KBs instead getting the whooole object).

Also I’m using Knockout to bind UI Elements with self.users observable array

7-31-2012 6-08-34 AM

  • You can use LINQ in JavaScript. Haha, Brilliant! For example if you have a users table and People table. And Each User is a Person. Lets see how to get Person Data if you clicked on a User.

7-31-2012 5-52-38 AM

First Param is a predicate that brings a person by Id.

this.Id ==> Passed in Second param as you see.

And Third one; is the callbacks from the operation. Awesome!

showPerson binded with list of users using Knockout JS (2nd image shows how I binded Div Element with showPerson function).

What else, See this video

http://nuget.org/packages/JayData

http://jaydata.org/

http://jaydata.org/api

Silverlight Tags Control Using RichTextBox, Popup and ListBox.

Leave a comment


 

Download Sample

 

 

Before couple of days I created a an editable tagging control with autocomplete list.
I decided to create one “some how” Smile similar to Live mail application “To” field.

to

That’s exactly what I need; RichTextBox, Popup Control, and a ListBox inside that popup, and SL Cinch MVVM Framework.

And one more thing InlineUIContainer that contains my Tag Item control.

InlineUIContainer object used to wrap FrameworkElement controls inside RichTextBox; so the only way to add (border, StackPanel, or even buttons) is by using this object.

Note:

Buttons will be disabled if RichTextBox ReadOnly property equal false.
So if you want to add delete button to your Tag Item; I think that you should to make your RichTextBox works in modes (Editable, ReadOnly).
Editable: to add inline tag items.
RedOnly: to click on delete buttons for each tag Item.

I did not like this kind of user experience. So I just delete delete button from tag item. Make things simpler that better Smile. You can just delete it using backspace or by highlighting some item then delete “As you saw in Video”.

 

When you download the sample, you will find a Silverlight library project called bunjeeb.SL.Controls

Three DLLs added to this project:

  • Microsoft.Expression.Interactions
  • System.Windows.Interactivity
  • Cinch.SL

You can find these three DLLs in dependencies folder with the sample.

As you see below TagTextBox is very simple:

<Grid x:Name="LayoutRoot">

<Popup x:Name="PopupTags" IsOpen="False">
<Grid>
<ListBox x:Name="PopupTagsList" Height="Auto" 
    MinWidth="200" MaxHeight="250"
    Background="White" 
    BorderBrush="Black" 
    KeyDown="PopupListBox_KeyDown"
    ItemContainerStyle="{StaticResource 
                          ListBoxItemContainerStyle}" 
    Padding="1,1,1,2"/>
</Grid>
</Popup>

<RichTextBox x:Name="rtb"
   AcceptsReturn="False"
   BorderBrush="{x:Null}" 
   Background="{x:Null}" BorderThickness="1,1,0,0">
   <i:Interaction.Triggers>
     <i:EventTrigger EventName="KeyUp">
      <Cinch:EventToCommandTrigger 
         Command="{Binding RichTextBoxKeyUp, 
                  ElementName=TagsTxtBox}"/>
     </i:EventTrigger>
     <i:EventTrigger EventName="KeyDown">
      <Cinch:EventToCommandTrigger 
         Command="{Binding RichTextBoxKeyDown,
                  ElementName=TagsTxtBox}"/>
     </i:EventTrigger>
     <i:EventTrigger EventName="ContentChanged">
      <Cinch:EventToCommandTrigger 
         Command="{Binding RichTextBoxContentChanged, 
                  ElementName=TagsTxtBox}"/>
     </i:EventTrigger>
     <i:EventTrigger EventName="LostFocus">
        <Cinch:EventToCommandTrigger 
         Command="{Binding RichTextBoxLostFocus, 
                  ElementName=TagsTxtBox}"/>
     </i:EventTrigger>
   </i:Interaction.Triggers>
</RichTextBox>

</Grid>

 

As you see here; I used EventToCommandTrigger to invoke these events using Commands. And that’s gonna help MVVMers to create there own ViewModel for that control. (If they want)

I’m sure that Sacha Barber (This one who creates Cinch Framework) used WeakReferences. and that gonna help GC to do his work. Smile Or simply you just use the delegate commands, or relay commands instead in PRISM. For me I prefer to use Cinch framework; I think it’s a preference.

TagsTextBox Control contains three properties:

  • Tags DependencyProperty: To display tags in RichTextBox.
  • AllTags DependencyProperty: Which contains all tags to display it on autocomplete popup.
  • InlineUITags CLR read only property: Which contains the Tag Items that you can find it in RichTextBox. 

When user starts typing FilterPopupList will be executed. The Main functionality of this Method is to:

  • Iterating into all InlineUIContainers to get tags texts.
  • Tags Popup will display = all tags except existing tags in RichTextBox.
private void FilterPopupList(string changedText)
{
   if (changedText == null)
   {
      PopupTagsList.ItemsSource = null;
      return;
   }

   //Get Tags from RichTextBox
   List<string> newTags = new List<string>();
   foreach (InlineUIContainer inlineUiContainer 
                in this.InlineUITags)
   {
     TextBlock tagNameTxtBlock = (TextBlock)((StackPanel)
      (((Border)inlineUiContainer.Child).Child)).Children[0];
            newTags.Add(tagNameTxtBlock.Text);
   }

   IEnumerable<string> tags = this.AllTags
                .Where(x => x.ToLower()
                         .Contains(changedText.ToLower()))
                                      .Except(newTags);

   PopupTagsList.ItemsSource = null;
   PopupTagsList.ItemsSource = tags;
}

 

When user commit tag insertion (by clicking enter or by choosing one of the items in the list); Then the source should be updated.

UpdateTagsPropertyAndBindingSource will do this work. Let me explain the logic
this method in three points.
  • Reset popup state if you want using isResetPopupState parameter.
  • Collecting the new added Tags.
  • Some Tags were deleted; so we should tell the source about it.
  • And Some tags were added; and we should tell the source about it also.
  • Update source using binding.UpdateSource()
  • And Finally, Raise TagsChanged event which contains Tags Added & Tags Deleted.

  • private void UpdateTagsPropertyAndBindingSource(
              bool isResetPopupState)
    {
          if (isResetPopupState)
             ResetPopupState();
    
          IEnumerable<string> newTags = GetNewItemsAdded();
    
          // If some item found in Tags Collection And 
          // not in RichTextBox; So we should delete it.
          IEnumerable<string> mustBeDeleted = 
                               this.Tags.Except(newTags);
          List<string> mustBeDeletedList = null;
    
          //Tags must be deleted from the source
          int mustBeDeletedCount = mustBeDeleted.Count();
          int lastRemoveIndex = mustBeDeletedCount - 1;
          if (mustBeDeletedCount > 0)
          {
             mustBeDeletedList = mustBeDeleted.ToList();
             for (int i = lastRemoveIndex; i >= 0; i--)
               this.Tags.Remove(mustBeDeletedList[i]);
          }
    
           //Tags must be added to the source
           IEnumerable<string> mustBeAdded = 
                                 newTags.Except(this.Tags);
           IEnumerable<string> mustBeAddedList = null;
           int mustBeAddedCount = mustBeAdded.Count();
           if (mustBeAddedCount > 0)
           {
             mustBeAddedList = mustBeAdded.ToList();
             foreach (string mustAddItem in mustBeAdded)
               this.Tags.Add(mustAddItem);
            }
    
            if (mustBeDeletedCount > 0 || mustBeAddedCount > 0)
            {
             BindingExpression binding = 
               this.GetBindingExpression(TagsTextBox.TagsProperty);
               if (null != binding) binding.UpdateSource();
    
               if (this.TagsChanged != null)
               {
                 TagsChanged(binding.DataItem, 
                   new TagsChangedArgs()
                 {
                    TagOwner = binding.DataItem,
                    TagsAdded = mustBeAddedList,
                    TagsDeleted = mustBeDeletedList
                 });
              }
         }
     }

Ok, One more thing to know, What If you have multiple instances of this control. And as you see in the video; that you can add entire new tag which is not listed in the auto complete popup list.

So how could tell other controls that All Tags List changed?

If sure that you folks have many many solutions in binding, Observable collection has the ability to notify the UI when item added. yeah you are right.

I decided to use the Mediator in Cinch framework. Its really amazing (pub sub mechanism) which is like Event Aggregator in PRISM.

So I just publish new All Tags List.

I just passed the Id to refocus RichTextBox.

[MediatorMessageSink(bunjeeb.SL.Common.MediatorMessages.
            TagsChangedMessage.TagsChanged)]
        public void CandidateTagsChangedMessage(
            Tuple<int, IEnumerable<string>, Type> tuple)
    {
       this.AllTags = tuple.Item2;

       PropertyInfo pinfo = tuple.Item3.GetProperty("Id");
       int currentId = (int)pinfo.GetValue(this.DataContext,
                                                null);
       int updatedId = tuple.Item1;

       if (updatedId == currentId)
           this.rtb.Focus();
  }

 

So the above code for the subscriber. And the publisher is our main view model.

public ICommand TagsChangedCommand { get; set; }
private void OnTagsChangedCommand(EventToCommandArgs args)
{
    TagsChangedArgs e = args.EventArgs as TagsChangedArgs;

    // TODO: Remove, add tags, Submit Changes to RIA Service
    // e.TagsAdded
    // e.TagsDeleted

    bunjeeb.SL.Common.MediatorMessages.TagsChangedMessage
       .Send(new Tuple<object>(e.TagOwner));
}

 

This command is binded with our TagsTextBox.TagsChanged Event

<bunjeebControls:TagsTextBox x:Name="MyTagsTextBox2"
   AllTags="{Binding AllTags}" 
   Tags="{Binding SomeTags2, Mode=TwoWay}" >

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="TagsChanged">
            <Cinch:EventToCommandTrigger 
        Command="{Binding TagsChangedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>

</bunjeebControls:TagsTextBox>

 

Sorry for not completing the 2nd article of pivot view control. I found that its more important to talk about Tagging Control. Since I did not any Silverlight Tagging Control.

That’s it. Wishing best coding in your life Smile

Download Sample

Silverlight Pivot View Control – Part 1

1 Comment


 

Download Sample

 

Just before one month from now, I worked with a new company; I really loved my new Job. New experience taken from Michael Ruddick; He is a Chief architect in T-Force.

I will not forget to talk about Tareq Amin “The Vise president in T-Force”. He is a big fan of the new Metro Apps style; Yeah Metro is amazing.

Tareq is listening to me a lot, sharing Ideas, respecting people.
Also he is studying to make Google’s 80/20 Innovation Model part of our work; or maybe to do like Innvoation Center in Amman Office; That’s really coool!

Ok, Lets talk about some geeky stuff here. Watch the video to see the output; And If you like it; Continue reading and download the sample from link below. Smile

 

Download Sample

 

 

I’ve just created a simple control, I called it Pivot View Control.

Simply this control contains

PivotViewControl:
this control divided into three parts:
- Title: Just a title for the Pivot Control (you can expose this property as a Dependency Property).
- Header: Contains Items Control for Tabs (or Pivot Headers).
- Content: Each header related with a UIElement which loaded in the Content Presenter.

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" MinHeight="30"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock TextWrapping="Wrap"
Text="Title, select one of items below"
VerticalAlignment="Center"
FontFamily="Segoe UI Semibold"
FontSize="21.333" Margin="7,0,0,0"/>
        <ListBox x:Name="PivotItemsHeaderList"
SelectedItem="{Binding SelectedItem, ElementName=PivotViewCtrl, 
Mode=TwoWay}"
                 Margin="0" Grid.Row="1"
Background="#00000000" BorderBrush="{x:Null}"
                 ItemsSource="{Binding Items, ElementName=PivotViewCtrl}"
                 ItemsPanel="{StaticResource ItemsPanelTemplate}"
                 ScrollViewer.VerticalScrollBarVisibility="Disabled"
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled"
          ItemContainerStyle="{StaticResource ListBoxItemContainerStyle}"
                 FontFamily="Segoe WP SemiLight" FontSize="24"
                 ItemTemplate="{StaticResource DataTemplateListItem}"/>
      <ContentPresenter x:Name="ContentPresenter" Margin="0" Grid.Row="2">
          <ContentPresenter.Projection>
              <PlaneProjection CenterOfRotationX="0"/>
          </ContentPresenter.Projection>
      </ContentPresenter>
    </Grid>

The animation createed using Visual State Manager, In the next version I’m going to add many animation options. For now this animation is good Smile.

Simply you can change the animation using Expression Blend, Go to states tab in blend and change the animation.

I have two states in my control;

GoAway: will hide current displayed content. And this animation completed I will change the content of it.

ComeIn: When GoAway animation completed and content changed.  Start the animation to bring the new content.

Anim

This is the animation completed Event:

void StoryBoardGoAway_Completed(object sender, EventArgs e)
{
   string headerValue = this.PivotItemsHeaderList.SelectedItem.ToString();
   var pivotItem = this.ItemsSource
        .SingleOrDefault(p => p.Header == headerValue);
   this.ContentPresenter.Content = (UIElement)pivotItem.Content;
   VisualStateManager.GoToState(this, "ComeIn", true);
}

PivotItemControl.cs

This control is a dependency control; Its something like Tab Item.

public class PivotItemControl : DependencyObject
    {
        public DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(String),
            typeof(PivotItemControl), null);
         public String Header
        {
            get
            {
                return (String)GetValue(HeaderProperty);
            }
            set
            {
                SetValue(HeaderProperty, value);
            }
        }
        public DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(UIElement),
            typeof(PivotItemControl), null);
         public UIElement Content
        {
            get
            {
                return (UIElement)GetValue(ContentProperty);
            }
            set
            {
                SetValue(ContentProperty, value);
            }
        }
    }

How to use it?

public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }
         void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            BindPivotItems();
            this.Loaded -= MainPage_Loaded;
        }
       private void BindPivotItems()
        {
          List<PivotItemControl> list = new List<PivotItemControl>();
          String[] headers = new string[] {"details","documents","notes"};
             foreach (string item in headers)
            {
                 list.Add(new PivotItemControl()
                        {
                            Header=item,
                            Content=new DummyContentControl() { Tag=item }
                        });
            }
           this.PivotViewControl.ItemsSource = list;
        }

Some enhancements could occurred; like using one Usercontrol as a Content; And Change the DataContent when GoAway Animation Completed. But I think you need to Expose an Event, Yeah that gonna be great.

My Experience with Mobile Ads

2 Comments


Salam Dears,

In the last months I was very busy; learnning Objective-C (iOS development). And the fruit comes with a simple application called Quraan Telawat.

You can find the link above in this page.  Anyway, one of the most interesting experience that i’ve got is the Ads.

Dude: what do you mean by Ads?
Me: Its an Advertising space that you reserve it in your application to browse Advertisements.

Dude: Are they advertising on your app? How did they know you?
Me: Actually, they do not know me. There are many known Ads providers in the world like google which have AdSense SDK, and AdFalcon for Noqush company.

Dude: ok, I see. Is it only for phones?
Me: nop, you can use it in your website, iOS apps, Android, and some of them are supporting WP7 also.

                _ _
Dude
: {$.$} … And what about the money?
Me: since 5th of November I’ve got around $43 … yeah not that much; but at the end its extra money comes from one app. In addition to the new experience.
I want to share with you this site which created by one of google’s team its called Guide to the App Galaxy

Dude: Interesting, Nice UI!!
Me: Yeah, It will answer all of your questions about monetizing your apps and some guidelines.

One more comment dude, I have till now 4,000 users. but actually not all of them are an active users now. so I found this wonderful tool that you can add it to your app and it will send to you the number of active users at this moment.

Dude: really!!
Its called Google Analytics. And you can download the SDK from here. This SDK is mentioned in that Guide Galaxy portal.

Dude: You said that there are many Ads providers. What should I use?
Me: Actually I found Admob really great.

Dude: Why?

Me: Let me share with you something

This image contains a stats for each day. Number of Impressions, Requests, Fill Rate, ..a

Dude: wait wait. Requests & Impressions … what is the deference?

Me: When a user open the app. … It will request an Ad.  but it could comes with Ad … And if it comes with Ad … Thats an Impression.

Dude: Is there a way to make sure that all requests comes Impressions?
Me: Yeah, AdMob already have this … they are also displaying Ads from AdSense .. And you can also handle this by code. So if there is no impassion display Ad from another provider. But its not the optimal way to solve this problem.

You can use “The mediator approach”… the mediator SDK will do the whole work and jumping between providers till it comes with an impression.

Its called AdWhirl … I did not use it till now but it seems great.

Wishing you a googd luck dude, Good night.
Dude: Good night.

MVVM with ASP.net Using knockout JS Library

4 Comments


Download Sample Code

If you are a WPF or Silverlight developer; you should be familiar with the fancy binding and notification Mechanisms in it.

MVVM pattern is dependent on these mechanisms to view data binding expressions.

Fortunately, Steven Sanderson created a brilliant library to use MVVM pattern with ASP.net and he called it Knockoutjs

What is Knockout library?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Knockout documentation

To learn this library you can start with this interactive tutorial http://learn.knockoutjs.com/

Now, Let’s do our first ASP.net application using this wonderful library

  • Create a new Empty Web Application. (Name it KOTest)
  • Create a new person class as follows
Public Class Person Private _FirstName As String Public Property FirstName() As String Get Return _FirstName
        End Get Set(ByVal value As String)
            _FirstName = value
        End Set End Property Private _LastName As String Public Property LastName() As String Get Return _LastName
        End Get Set(ByVal value As String)
            _LastName = value
        End Set End Property Private _Age As String Public Property Age() As String Get Return _Age
        End Get Set(ByVal value As String)
            _Age = value
        End Set End Property End Class 
  • Add a web Service (ASMX Service) and call it ViewModelService.asmx
  • After adding this service uncomment the first line
<System.Web.Script.Services.ScriptService()> _
  • And Paste this method to it.
    <WebMethod()> _
    Public Function GetPerson() As Person   Return New Person() With {
            .FirstName = "Mohammad",
            .LastName = "Najeeb",
            .Age = "27" }
    End Function
    • Add a new Web form page (call it ko.aspx).
    • Import two javascript libraries
      • jQuery 1.4.1 (You can download it from here)
      • knockout 1.2.1 (You can download it from here)
      • You can also add jQuery templates but I did not use it in my sample here (You can download it from here)
    <script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="JS/knockout-1.2.1.js" type="text/javascript"></script>
  • Now, Let’s create a person class in javascript
// Create a Person Class with Constructor  // that takes two parameters (First Name & Last Name) var person = function (fName, lName) {
    this.FirstName = ko.observable(fName),
    this.LastName = ko.observable(lName),
    this.Age = 0
};

As you see above. FirstName property and LastName property are Observables.

Observables (like FirstName and LastName) will notify the UI when they changed in viewModel object.

So the previous implementation for person class in javascript is similar to TwoWay binding in WPF.

If FirstName and LastName are not observables; The UI will display the values at the first time. but any change occurred in property will not be reflected to the UI.

Removing Observables from FirstName & LastName similar to OneTime binding mode in WPF.

Screen Shot 2011-07-30 at 8.59.59 PM
So if you want to do a OneTime binding change your person implementation in  JavaScript to be like this

var person = function (fName, lName) {
    this.FirstName = fName,
    this.LastName = lName,
    this.Age = 0
};

But viewModel is not binded to the UI till now!! And this is our next step.

  • Bind viewModel object to the UI & get the values from Server by calling the web service.
jQuery(function () {
    ko.applyBindings(viewModel);
    KOTest.ViewModelService.GetPerson(onSuccess,
                                      onFail,
                                      null, null);
});
  • As you know you need a Script manager to call the service. So please just add it at the top of the page inside the form tag.
  • When calling service succeeded; just set viewModel.person property
function onSuccess(result) {
            viewModel.person(new person(
                             result.FirstName,
                             result.LastName
                             ));
        }
  • Paste add this HTML in you page
<div<div> <label for="<%=txtFirstName.ClientID %>"> First Name</label> <asp:TextBox ID="txtFirstName" runat="server"  data-bind="value:person().FirstName"> </asp:TextBox> </div> <div> <label for="<%=txtLastName.ClientID %>"> Last Name</label> <asp:TextBox ID="txtLastName" runat="server"  data-bind="value:person().LastName"> </asp:TextBox> </div> <div> <asp:Button ID="btnSubmit" runat="server"  Text="Submit" /> </div> </div> 

This is all what I have for Now. And Another Happy Weekend had been finished Sad smile. Happy Ramadan for all. And See ya later.

Step by Step – Filtering List using Reactive Extensions (Rx Framework)

Leave a comment


  1. Download Rx Framework from here.
  2. Install it.
  3. Create New Windows Forms project (you can choose WPF, Silverlight, WP7). I used WinForms in my example.
  4. Add TextBox and ListBox to it as you see below.

Screen shot 2011-07-14 at 1.50.46 AM

  5.   Add System.Reactive reference to your project (see image below).

Screen shot 2011-07-14 at 1.53.05 AM

6.  Create any dummy data (you can use any repository you want) and just to make things fast Smile

Screen shot 2011-07-14 at 1.51.58 AM

7. Add this chunk of code.

Screen shot 2011-07-14 at 1.52.17 AM

When TextChanged raised the subscribed code will be executed Asynchronously.

That’s it. As simple as that.

Good night. Smile

ASP.net Grid View with jQuery Ajax (Dynamic Load for ASCX HTML)

9 Comments


After a couple of months without touching anything related to WEB. I’m doing some refreshment by creating Web Diagram Tool using jQuery “Something like Visio on WEB”.

Also my brother asked me to help to him to do a paging using AJAX.

I found some articles that used Update Panel …Yuk!!! .. Come-on people! are you still use it!! Update Panel could be useful sometimes. But its not a full AJAX. It will create a request for the whole page and when response comes back; It will refresh the part which in update panel.

I did something deferent and better. Its not new at all. Actually I worked on this task before a couple of years; I’m doing some refreshment, my brother just triggered me when he ask.

Simply, I loaded the Usercontrol  dynamically. and the Usercontrol contains anything you want (in my case it’s a GridView). Tada! pretty easy.

to load controls dynamically use this static method. I you want to use it; just modify it by adding your control and set your own properties.

private static String GetGridControlContent(String controlLocation,
 int pgIndex, int pgSize)
 {
   var page = new Page();

   var userControl = (MyGridView)page.LoadControl(controlLocation);

   if (pgIndex < 0)
         pgIndex = 0;

   userControl.PageSize = pgSize;
   userControl.PageIndex = pgIndex;

   page.Controls.Add(userControl);

   String htmlContent = "";

   using (var textWriter = new StringWriter())
   {
    HttpContext.Current.Server.Execute(page, textWriter, false);
    htmlContent = textWriter.ToString();
   }
   return htmlContent;
 }

 

As you see above; you can pass any parameter to the Usercontrol by creating a properties in that user control. For me I created PageSize & PageIndex properties.

You can wrap this method in a web method to call it from Javascript.

[WebMethod]
public static string AjaxGetGridCtrl(int pgIndex, int pgSize)
{
     return GetGridControlContent("~/MyGridView.ascx", pgIndex, 
                                  pgSize);
}

 

So you can load you control using script mnager or using jQuery AJAX library. I used the 2nd choice

$.ajax({
    type: 'POST',
    url: 'MyDefault.aspx/AjaxGetGridCtrl',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
       $('#mainDiv').html(data.d);
    },
    data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"
 });

 

 

jQuery AJAX is really nice. Let’s talk more about the options above.

type: you choose you either GET, or POST options.

url: I request this URL using POST.

contentType: used when you want to send data to the server (data is the last option). is this case the data will be sent in JSON format with UTF-8 Encoding.

dataType: The type of data that you’re expecting back from the server.

success: response will be handled here; if request succeeded.

I n this example; the HTML result will be rendered in mainDiv element.

data: parameters will be sent to the web method here.

Current Page Index and Page Size are stored in a Hidden Fields. And when user clicked on Next button; the value will be added by 1. And the AJAX call started by sending the new PageIndex.

 

function FillGrid(flag) {

 var pgIndex = 0;
 var pgCurrentIndex = $('#txtPgIndex').attr('value');
 var pgSize = $('#txtPgSize').attr('value');

 switch (flag) {
      case 'prev':
          pgIndex = parseInt(pgCurrentIndex) - 1;
          break;
      case 'next':
          pgIndex = parseInt(pgCurrentIndex) + 1;
                    break;
            }

            $('#txtPgIndex').attr('value',pgIndex);

      $.ajax({
           type: 'POST',
           url: 'MyDefault.aspx/AjaxGetGridCtrl',
           contentType: "application/json; charset=utf-8",
           dataType: 'json',
           success: function (data) {
               $('#mainDiv').html(data.d);
           },
           data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"
       });
    }

 

Calling GetGridControlContent will cause a crahs at this line

 
HttpContext.Current.Server.Execute(page, textWriter, false);
 
 
To avoid this crash; all you need to do is to add
a [run at server form tag] to your Usercontrol
 
 
<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="MyGridView.ascx.cs" 
    Inherits="test.MyGridView" %>
<form id="form1" runat="server">
<asp:GridView ID="gv" runat="server" AllowPaging="true" 
              AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ID" 
               HeaderText="First Name" Visible="false" />
        <asp:BoundField DataField="FirstName" 
               HeaderText="First Name" />
        <asp:BoundField DataField="LastName"
               HeaderText="Last Name" />
        <asp:BoundField DataField="Mobile" 
               HeaderText="Mobile" />
        <asp:BoundField DataField="EmpSalary" 
               HeaderText="Salary" />
        <asp:BoundField DataField="HiringDate" 
               HeaderText="Hiring Date" />
        <asp:BoundField DataField="DOB" 
               HeaderText="Date of Birth" />
    </Columns>
</asp:GridView>
<div id="pgingFooter">
    <a href="javascript:void(0);" id="prev">Previous</a> 
        &nbsp;|&nbsp; <a href="javascript:void(0);"
        id="next">Next</a>
</div>

</form>

 

And there is no magical things in the code behind for this user control, Just fill your GridView Control according to PageIndex & PageSize properties.

public partial class MyGridView : System.Web.UI.UserControl
    {
        private List<Employee> lstEmployees;

        public int PageSize { get; set; }
        public int PageIndex { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            lstEmployees = new List<Employee>();

            FillList();
            lstEmployees = 
                       lstEmployees.Skip(this.PageIndex * this.PageSize)
                                   .Take(this.PageSize).ToList();

            gv.DataSource = lstEmployees;
            gv.DataBind();
        }

        private void FillList()
        {
            for (int j = 1; j <= 100; j++)
            {
                lstEmployees.Add(new Employee { 
                     ID = j, FirstName = "First" + j, 
                     LastName = "Last" + j, 
                     Mobile = "+932 55 1212" + j, 
                     EmpSalary = j * 100, 
                     DOB = "12/12/1990", 
                     iringDate = "12/12/2010" });
            }
        }
    }

 

You can download the sample from here

Older Entries

Follow

Get every new post delivered to your Inbox.