ASP.Net ListView call javascript, css class

Today I’ve used the Asp.Net ListView control, It’s very easy to use but there are many thing to know to obtain the best result.

In this post I’ll explain how to bind the value to show and how to call javascript function.

For all developer who usually use WPF and Silverlight this approach is very similar to the bind to ViewModel or Model.

My suggestion is to realyze an approach MVC “like”:

  1. in the code behind contact the DAL (Data Access Layer) and request all data you need
  2. wrap each data in your Model class that expose ANY property you need to use in the View.
  3. in the .aspx file “bind” the property you need

Next the code I used in a project to work with Active Directory
My model ADEntity.cs:

public class ADEntity
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string DisplayName { get; set; }
        public string SAMAccountName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsLocked { get; set; }
        public bool IsDisabled { get; set; }
        public bool IsInternetEnabled { get; set; }
        public string Path { get; set; }
        public string OuName 
        {
            get 
            {
                string[] results = Path.Split(',');
                string strResult = string.Empty;

                if (results.Length >= 2)
                    strResult = results[1].Replace("OU=", string.Empty);

                return strResult;
            } 
        }

        public string PathEncoded
        { 
            get
            {
                return HttpContext.Current.Server.UrlEncode(Path);
            }
        }

        public string PathHTMLEncoded
        {
            get
            {
                return HttpContext.Current.Server.HtmlEncode(Path);
            }
        }

        public string SAMAEncoded
        {
            get
            {
                return HttpContext.Current.Server.UrlEncode(SAMAccountName);
            }
        }

        public string trClass
        {
            get
            {
                string strClass = string.Empty;

                if (IsLocked)
                    strClass += "locked ";
                if (IsDisabled)
                    strClass += "disabled ";

                return strClass.Trim();
            }
        }

        public string imgDisabled
        {
            get
            {
                return "Images/Icon/" + ((IsDisabled) ? "iconDisabled.png" : "iconEnabled.png");
            }
        }

        public string imgInternet
        {
            get
            {
                return "Images/Icon/" + ((IsInternetEnabled) ? "iconEnabled.png" : "iconDisabled.png");
            }
        }

        public string UnlockClientFunction
        {
            get { return "return unlockUser(this,'" + SAMAEncoded + "');"; }
        }


        public string EnableDisableClientFunction
        {
            get
            {
                if (IsDisabled)
                    return "return enableUser(this, '" + SAMAEncoded + "');";
                else
                    return "return disableUser(this, '" + SAMAEncoded + "');";
            }
        }


        public string AddRemoveInternetGroupClientFunction
        {
            get
            {
                if (IsInternetEnabled)
                    return "return removeInternetGroup(this, '" + SAMAEncoded + "');";
                else
                    return "return addInternetGroup(this, '" + SAMAEncoded + "');";
            }
        }

        public string ResetPswLink
        {
            get
            {
                return "ResetPassword.aspx?sama=" + SAMAEncoded;
            }
        }
    }

My user control code behind UCSearchBoxResult.ascx.cs

foreach (SearchResult item in results)
                {
                    entityTmp = new ADEntity();
                    entityTmp.Name = ADUtils.GetProperty(item, "name");
                    entityTmp.Description = ADUtils.GetProperty(item, "description");
                    entityTmp.DisplayName = ADUtils.GetProperty(item, "displayName");
                    entityTmp.SAMAccountName = ADUtils.GetProperty(item, "SAMAccountName");
                    entityTmp.FirstName = ADUtils.GetProperty(item, "GivenName");
                    entityTmp.LastName = ADUtils.GetProperty(item, "Sn");
                    entityTmp.IsLocked = ADUtils.IsLocked(item.Path);
                    entityTmp.IsDisabled = ADUtils.IsDisabled(item.Path);
                    entityTmp.Path = item.Path;

                    entityTmp.IsInternetEnabled = false;
                    _listEntity.Add(entityTmp);
                }

                ListViewResult.DataSource = _listEntity.OrderBy(item => item.OuName).ThenBy(item => item.SAMAccountName);
                ListViewResult.DataBind();

results is the result from Active Directory FindAll method but can be the result from a Sql query.
In foreach block I create an instance of my model class foreach results.
I fill any property of my moden and I put it in a list
After the foreach block is necessary set the DataSource with the list (in this case sorted) and call DataBind() method.

UCSearchBoxResult.ascx

    <asp:ListView ID="ListViewResult" runat="server" ItemPlaceholderID="itemContainer">
        <LayoutTemplate>
            <table style="width:99%" cellspacing="0" >
                <thead>
                    <tr>
                        <th class="line">Login</th>
                        <th class="line" style="width:80px">Enabled</th>
                        <th class="line" style="width:80px">Locked</th>
                        <th class="line" style="width:80px">Internet</th>
                        <th class="line" style="width:100px">password</th>
                        <th class="line">Nome</th>
                        <th class="line">Cognome</th>
                        <th class="line">Agenzia</th>
                    </tr>
                </thead>
                <tbody id="itemContainer" runat="server"></tbody>
            </table>
        </LayoutTemplate>
        <ItemTemplate>
            <tr id="Tr1" runat="server" class='<% #Eval("trClass")%>'>
                <td class="line">
                    <asp:Literal ID="lblCompany" runat="server" Text='<% #Eval("SAMAccountName")%>'></asp:Literal>
                    &nbsp;
                </td>
                <td class="line">
                    <img id="Img1" src='<% #Eval("imgDisabled")%>' runat="server" class="imgClick"
                            onclick='<% #Eval("EnableDisableClientFunction")%>'/>
                </td>

                <td class="line" style="width:45px;margin-right:5px">
                    <img id="Img2" src="Images/Icon/lock-icon.png" runat="server" class="imgClick" alt="locked" onclick='<% #Eval("UnlockClientFunction")%>' Visible='<% #Convert.ToBoolean(Eval("IsLocked"))%>'/>
                    &nbsp;
                </td>

                <td class="line">
                    <img id="Img3" src='<% #Eval("imgInternet") %>' runat="server" class="imgClick"
                            onclick='<% #Eval("AddRemoveInternetGroupClientFunction")%>'/>
                </td>

                <td class="line">
                    <a id="A1" runat="server" href='<% #Eval("ResetPswLink")%>' class="linkReset">Reset</a>
                </td>

                <td class="line">
                    <asp:Literal ID="literal1" runat="server" Text='<% #Eval("FirstName")%>'/>
                    &nbsp;
                </td>
                <td class="line">
                    <asp:Literal ID="literal2" runat="server" Text='<% #Eval("LastName")%>'/>
                    &nbsp;
                </td>
                <td class="line">
                    <asp:Literal ID="literal3" runat="server" Text='<% #Eval("OuName")%>'/>
                    &nbsp;
                </td>
            </tr>
        </ItemTemplate>
    </asp:ListView>

In this sample (not so easy) It’s possible see any problematic present in the real work

ListView Bind to Simple property with Eval

On the online sample is usuale show only how to bind with a property to show like this

<asp:Literal ID="literal3" runat="server" Text='<% #Eval("OuName")%>'/>

NOTE:

  1. Use the single quota ‘ not the usal ” to wrap #Eval
  2. To apply the eval is necessary the item is runat=”server”

Apply a CSS class depending by some value

If you have to choose a CSS class to apply to the row how can we do?
The work will not implemented in the .aspx file but in the code behind or in Model class.
Is not possible concat some evaluation so any code must be in che code behind
Here an example to determine the right tr class

.aspx

<tr id="Tr1" runat="server" class='<% #Eval("trClass")%>'>

ADEntity.cs

        public string trClass
        {
            get
            {
                string strClass = string.Empty;

                if (IsLocked)
                    strClass += "locked ";
                if (IsDisabled)
                    strClass += "disabled ";

                return strClass.Trim();
            }
        }

As you can see the tr have to be runat=”server” also if it’s an HTML standard tag

Hide or Display, change visibility of some block

To change the visibility you can apply some css class as I show before with display:none or display:block.
If we don’t want send to the client the “item” at all, we can use the asp.net Visibile boolean property and binding it as string property.

<img id="Img2" src="Images/Icon/lock-icon.png" runat="server" 
      class="imgClick" alt="locked" onclick='<% #Eval("UnlockClientFunction")%>' 
      Visible='<% #Convert.ToBoolean(Eval("IsLocked"))%>'/>

ADEntity.cs

public bool IsLocked { get; set; }

Note the use of Convert.ToBoolean()

Call a javascript

.aspx

<script ....>

    function unlockUser(sender, sama) {
        $.ajax({
            type: "GET",
            dataType: "text",
            cache: false,
            url: "ADAdminHandler.ashx?sama=" + sama + "&action=unlock",
            beforeSend: function () { },
            complete: function () { },
            error: function (xhr, status, errorThrown) {
                alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
            },
            success: function (result) {
                // se andanto a buon fine (controllo fasullo)
                if (result == "1") {
                    // nascondo l' img
                    $(sender).hide();

                    $(sender).parents("tr").removeClass("locked");
                }
                else
                    alert("Error: " + result);
            }
        });
    }

</script>


<img id="Img2" src="Images/Icon/lock-icon.png" runat="server" 
      class="imgClick" alt="locked" onclick='<% #Eval("UnlockClientFunction")%>' 
      Visible='<% #Convert.ToBoolean(Eval("IsLocked"))%>'/>

ADEntity.cs

        public string SAMAEncoded
        {
            get
            {
                return HttpContext.Current.Server.UrlEncode(SAMAccountName);
            }
        }

        public string UnlockClientFunction
        {
            get { return "return unlockUser(this,'" + SAMAEncoded + "');"; }
        }

The code show that the real javascript string to insert in the onlick attribute of the img tag is calculated in the code behind.
Other important thing to note is that in my javascript funciont I’ll pass the samaccount name with querystring to a generic handler. Because I’ll pass it in query string it’s important to Encode the parameters. Also this operation will performed in the code behind

Conclusion

Anything you need to “write” in the .aspx need to be solved in the codebehind!!!

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in Asp.Net, c#, MVC e contrassegnata con , , . Contrassegna il permalink.

Una risposta a ASP.Net ListView call javascript, css class

  1. Pingback: ASP.Net ListView call method or pass row object | Un programmatore tra i cordoli

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...