Mar 07

Comparing span text in jquery and asp.net

Print Friendly

This post has 458 words. It will take approximately 4 minutes, 34 secondes for reading it.

Recently in one of my web application I wanted to disable a button depending on the value in html span. Basically my idea is to enable and disable publish button in my web application depending on span text value.

 

In this asp.net web application, user update information as required then click on apply change button. Apply change button update the record in MS Sql server database also change the publish flag to No. Now user will be able to see a publish button, this button event basically publish data in external source. When user click on publish data button this will push the data into external server and update the record matching with the primary key. It will also update the local database record only changed the flag to Yes so that user would not able to publish this record again unless they do any other changes.

 

Here is the html code for span text -

<table>
<tr><th>Sync Status: </th><td colspan="3"><asp:Label ID="lblSync" runat="server" Text='<%# Eval("SYNC") %>' /> </td></tr>
<tr><td colspan="3"><asp:Button ID="btnPublish"
        runat="server" Text="Publish to RecData" OnClick="btnPublish_Click" /> </td></tr>
</table>

Important!

Print Friendly

This post has 32 words. It will take approximately 19 secondes for reading it.

I have stripped out all the other html code just to focus on this example. You notice I am using asp label control here which renders as span field in html source.

 

The above label rendered the page with span tag and text of the label text value.

<table>
<tr><th>Sync Status: </th><td colspan="3"><span id="MainContent_FormView1_lblSync">Yes       </span> </td></tr>
<tr><td colspan="3"><input type="submit" name="ctl00$MainContent$FormView1$btnPublish" value="Publish to RecData" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContent$FormView1$btnPublish&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="MainContent_FormView1_btnPublish" />
</td></tr>
</table>

Here is my jQuery script to grab the span value and set the button property.

<script type="text/javascript">
        $(function () {

            $("#tabs").tabs();

            var sync = $("#MainContent_FormView1_lblSync").text();

            if ($.trim(sync) != "No") {
                alert(sync);
                $("#MainContent_FormView1_btnPublish").attr("disabled", "disabled");
            }

        });
    </script>

Now when the span text is Yes the button get disabled and for anything else it is enabled.

This is the working screen shot -

 

 

Feb 28

Databind in checkbox list in ASP.NET

Print Friendly

This post has 1322 words. It will take approximately 13 minutes, 13 secondes for reading it.

Checkbox list does not support multiple databind. To be a bit clearer, it does not support databind for multi select in checkbox list. It only stores one entry from the checkbox list.

In one of my recent project I had to implement checkbox list where user can tick multiple checkboxes and store them into the database table. In this project I was using SQL server express database and storing the data using the data in colon (:) delimited value so that I can push the data back into Oracle database to use this in Oracle APEX application. You can store your data whatever fashion you want to save in. In oracle APEX application it is an in build feature where you can bind data dynamically in checkbox list. Unfortunately you can not do this in ASP.NET.

Lets start the task, I have used SqlDataSource for database operation in this example and connection string pulled from web.config file. Here is my SqlDataSource structure -

<asp:SqlDataSource ID="dsImported" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
        SelectCommand="SELECT * FROM [rtt_sites] where sit_id=@sit_id" UpdateCommand="update rtt_sites set name=@name, sit_type=@sit_type, status=@status, primary_function=@primary_function, fee_type=@fee_type, access_type=@access_type, update_date=getdate() where sit_id=@sit_id">
        <UpdateParameters>
            <asp:Parameter Name="sit_id" Type="Decimal" />
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="status" Type="String" />
            <asp:Parameter Name="primary_function" Type="String" />
        </UpdateParameters>
        <SelectParameters>
            <asp:QueryStringParameter QueryStringField="sit" Name="sit_id" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>

In the above sqldatasource I am actually using a query string to fetch data in a Formview. User can update or change record if they want to. Now here is my formview structure -

<asp:FormView ID="FormView1" runat="server" AllowPaging="True"
        DataKeyNames="recId" DataSourceID="dsImported" DefaultMode="Edit"
        Width="100%">
        <EditItemTemplate>

        <table cellpadding="3" cellspacing="3" >
        <tr><th>Record Id:</th><td><asp:Label ID="Label1" runat="server" Text='<%# Eval("recId") %>' /></td></tr>
<tr><th>Site Id:</th><td><asp:TextBox ID="sit_idTextBox" runat="server" Text='<%# Bind("sit_id") %>' ReadOnly="true" /></td></tr>
<tr><th>Site Name:</th><td><asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' ReadOnly="true" Width="400" /></td></tr>
<tr><th>Site Type: </th><td>
    <asp:CheckBoxList ID="chkSiteType" runat="server" RepeatColumns="5" DataSourceID="dsSiteType"
        DataTextField="description" DataValueField="returnVal">
    </asp:CheckBoxList>

        <tr><th>Status:</th><td>
            <asp:DropDownList ID="dlStatus" runat="server" selectedValue='<%# Bind("status") %>' >
            <asp:ListItem  Text="Select status" Value="" />
            <asp:ListItem Text="Current" Value="CURRENT" />
            <asp:ListItem Text="Closed" Value="CLOSED" />

            </asp:DropDownList>
        </td></tr>
<tr><th>Primary function:</th><td>
    <asp:DropDownList ID="dlPrimaryFunction" runat="server"
        selectedValue='<%# Bind("primary_function") %>' DataSourceID="dsSiteType"
        DataTextField="description" DataValueField="returnVal" AppendDataBoundItems="true" >
    <asp:ListItem Value="" Text="Select function" />

    </asp:DropDownList>
</td></tr>
<tr><th>Longitude: </th><td><asp:TextBox ID="txtLongitude" runat="server" Text='<%# Bind("longitude") %>' Width="200" /></td></tr>
        <tr><th>Latitude: </th><td><asp:TextBox ID="txtLatitude" runat="server" Text='<%# Bind("latitude") %>' Width="200" /></td></tr>
        <tr><th>Fee Type:</th><td>
            <asp:CheckBoxList ID="chkFeeType" runat="server" RepeatColumns="6">
                <asp:ListItem Value="ANOFEES">No Fees</asp:ListItem>
                <asp:ListItem Value="BOAT">Boat Tour</asp:ListItem>
                <asp:ListItem Value="PARK">Park Entry</asp:ListItem>
                <asp:ListItem Value="CAMPING">Camping</asp:ListItem>
                <asp:ListItem Value="CAVING">Caving</asp:ListItem>
                <asp:ListItem Value="SITE">Site Entry</asp:ListItem>

            </asp:CheckBoxList>
        </td></tr>
        <tr><th>Access Type: </th><td><asp:CheckBoxList ID="chkAccessType" runat="server"
                RepeatColumns="7">
            <asp:ListItem Value="BICYCLE">Bicycle</asp:ListItem>
            <asp:ListItem Value="BUS">Bus</asp:ListItem>
            <asp:ListItem Value="CANOE">Canoe</asp:ListItem>
            <asp:ListItem Value="CAR">Car</asp:ListItem>
            <asp:ListItem Value="CARAVAN">Caravan</asp:ListItem>
            <asp:ListItem Value="AIRCRAFT">Fixed Wing Aircraft</asp:ListItem>
            <asp:ListItem Value="FOOT">Foot</asp:ListItem>
            <asp:ListItem Value="4WD">Four Wheel Drive</asp:ListItem>
            <asp:ListItem Value="HELICOPTER">Helicopter</asp:ListItem>
            <asp:ListItem Value="HORSE">Horse</asp:ListItem>
            <asp:ListItem Value="PWR_BOAT">Power Boat</asp:ListItem>
            <asp:ListItem Value="SAIL_BOAT">Sail Boat</asp:ListItem>
            <asp:ListItem Value="Bike">Trail Bike</asp:ListItem>
            </asp:CheckBoxList> </td></tr>
<tr><th>Created on: </th><td><asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("create_date") %>'  ReadOnly="true"  /></td></tr>
<tr><th>Last updated: </th><td><asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("update_date") %>' ReadOnly="true" /></td></tr>
<tr><th>Created on: </th><td></td></tr>
<tr><th>Created on: </th><td></td></tr>
<tr><th>Created on: </th><td></td></tr>
        </table>
            <asp:Label ID="lblFeetype" runat="server" Text='<%# Eval("fee_type") %>' Visible="false" /> <br />
            <asp:Label ID="lblAccessType" runat="server" Text='<%# Eval("access_type") %>' Visible="false" /> <br />
           <asp:Label ID="lblSiteType" runat="server" Text='<%# Eval("sit_type") %>' Visible="false" />
            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                CommandName="Update" Text="Update" />
            &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server"
                CausesValidation="False" PostBackUrl="~/importSite.aspx" Text="Cancel" />

                <asp:SqlDataSource ID="dsSiteType" runat="server"
        ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
        SelectCommand="SELECT [description], [returnVal] FROM [rtt_param] WHERE ([CODE] = @CODE)">
        <SelectParameters>
            <asp:Parameter DefaultValue="SITE_TYPE" Name="CODE" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>
        </EditItemTemplate>

    </asp:FormView>
    <asp:Label ID="lblMsg" runat="server" ></asp:Label>
<br />

Now in the above formview I also have couple of dynamic dropdown list populated from database table. Hope it is easy to understand. If you look at the above code closely, you will notice I have binded data in all textbox and dropdown list controls however I did not bind data in checkbox list control at this stage.

Read the rest of this entry »

Feb 23

Calling webservice in Ajax using jQuery in ASP.NET

Print Friendly

This post has 529 words. It will take approximately 5 minutes, 17 secondes for reading it.

In this example I have shown how to call a web-service using jQuery AJAX. For instance I wanted to load some addition information or external information in my website using web-service and Ajax call. If you do not know how to create a web-service then you open your website in Visual Web Developer 2005/2008/2010 right click on the root directory in file browsing (explorer) window and click on add new item. Select web-service from the suggested list and name it whatever you like. Usually it places the code file in APP_CODE folder. I have created a simple web-service called myService.asmx, here is my code -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for myService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class myService : System.Web.Services.WebService {

    public myService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string cityWeather(string city)
    {

        if (city=="Dhaka")
            return "City: " + city + "- Sunny. This is the time to go out and have fun. fsd";
        else
        return
            "City:" + city + "- Cloudy";

    }

}

The purpose of this web-service to display some information depending on user input in URL query string. Basically the URL will include a city name and web-service will display the weather information for that city. I have tried to make this simple to understand.

Once my web-service is ready, I have called the web service from aspx page using jQuery Ajax. First include the jquery script in the header section of your aspx page. If you don’t have jquery file then you can download it from jQuery website.

<head>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

</head>
<body>
<h2>AJAX call using jQuery in ASP.NET </h2>

</body>

To grab the query string parameter I had write a javascript function, you might do it in different way. I have used only java to accomplish this functionality.

        // Read a page's GET URL variables and return them as an associative array.
        function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

 

Here is the code of AJAX call in my aspx page -

var ct=getUrlVars()["name"] ;

        $.ajax({
            url: "services/myService.asmx/cityWeather",
            dataType: "html", // data type can have text
            type: "post",
            data: { city: ct },
            error: function (err) {
                alert("Error: " + err.toString());
            },
            success: function (data) {
                $("#cityWeather").html(data);
            },
            async: false,
            timeout: 2000

        });

 

In the jQuery ajax call, I am calling the cityWeather function from myService.asmx page using URL parameter name.

I also have a html div to display or load the content. Here is the div code -

<div id="cityWeather">

</div>

Read the rest of this entry »

Feb 09

Fancybox in APEX dynamic report

Print Friendly

This post has 493 words. It will take approximately 4 minutes, 55 secondes for reading it.

Using fancybox in Oracle Application Express (APEX) can increase the page load performance specially when You have lot of items in one page and user needs to scroll down to reach the bottom which is quite annoying for some users. You can split your long page scrolling content into few pages and use link to open these additional information on demand using fancy box. So you are not leaving the main page but you can still access additional resources if you want to. It is working so good so far for me. Read my previous article if you do not know how to implement fancybox in APEX.

Now when it comes to the point where I wanted to implement fancybox in APEX dynamic report. Basically what I am trying to do in my report is – provide URL link for relevant image and display the image in fancybox when user click on it.

It works good when I load the page and rendered the report with the following code -

<script type="text/javascript">

$(document).ready(function(){
          $("a.fancyImg").fancybox({
                                   'transitionIn'	: 200,
                                    'transitionOut'	: 200
                                   });
                          });
</script>

The fancybox functionality breaks when partial post back happened into the page. So when I want to do column sorting or perform any other action in dynamic report fancybox link does not work. I understand that because my function only called once on document ready and it does not work for partial page load. Here is the screen capture of my report.

I have used custom SQL report query for URL link column. Here is the sample if you want to know how -

SELECT F.FAC_ID,
       F.FAC_TYPE,
       F.LOCATION,
       F.FAC_ASSET_DESC "Description",
       F.FAC_ASSET_NO "Asset No",
       F.FAC_ASSET_CONDITION "Condition",
       F.FAC_REPLACEMENT_COST "Initial Cost",
       F.REPLACEMENT_COST_TODAY "Todays Cost",
       F.FAC_LATITUDE_DEC "Latitude",
       F.FAC_LONGITUDE_DEC "Longitude",
       CASE
          WHEN fil.fil_id IS NOT NULL
          THEN
                '<a class="fancyImg" href="f?p=&APP_ID.:44:&SESSION.:::44:P44_FIL_ID:'
             ¦¦ fil_id
             ¦¦ '">View Image</a>'
          ELSE
             'No image'
       END
          Image
  FROM FACILITIES F, BUILDINGS B, FILES FIL
 WHERE     F.FAC_ID = B.FAC_ID(+)
       AND F.FAC_TYPE = 'BUILDING'
       AND FIL.SOURCE_ID(+) = F.FAC_ID

Now I have changed my javascript to use without document ready function. Here is the code -

<script type="text/javascript">

function fancyGallery(){
$("a.fancyImg").fancybox({
   'transitionIn'		: 200,
   'transitionOut'		: 200
});
}
</script>

Call this function in the report dynamically in onClick event.

CASE
          WHEN fil.fil_id IS NOT NULL
          THEN
                '<a class="fancyImg" onClick="javascript:fancyGallery();" href="f?p=&APP_ID.:44:&SESSION.:::44:P44_FIL_ID:'
             ¦¦ fil_id
             ¦¦ '">View Image</a>'
          ELSE
             'No image'
       END
          Image

It works fine in IE but I am not sure about FireFox.

 

 

Feb 01

Implementing fancybox in oracle APEX application

Print Friendly

This post has 211 words. It will take approximately 2 minutes, 6 secondes for reading it.

Recently in one of my application I have implemented Fancybox to give better user experience. I guess this is quite useful when you have too many items in one page and user has to scroll down to view details in the page. This will give better user experience hiding extra stuff from the page and make it available on demand or request.

I wanted to implement this functionality because in my relational database I have a master table which holds most of the common fields and I have created some child tables for store extra information for different types of assets e.g. furniture, building, structure etc. Instead of sending user to different page to enter additional information, I wanted to give a bit flexibility so that user will be in the same page and they can enter details of specific asset information in fancy popup window if they want to. It will also give a bit better experience in terms of page load as it will load only necessary fields. The page looks like this -

First of all, you have to download the script from http://fancybox.net and Once you downloaded zip file, extract it where ever the location you like.

Read the rest of this entry »

Page 1 of 512345