แสดงบทความที่มีป้ายกำกับ ASP.NET AJAX แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ ASP.NET AJAX แสดงบทความทั้งหมด

วันพฤหัสบดีที่ ๓ มิถุนายน พ.ศ. ๒๕๕๓

ScriptMode ของ ScriptManager ต่างกันอย่างไร

วันนี้เจอคำถามที่ GreatFriends เรื่อง ScriptMode ของ ScriptManager ซึ่งผมตอบไปแล้ว แต่ก็จะมาขยายความเพิ่มใน blog นี้ละกันครับ

ใน ScriptManager จะมี Property ตัวหนึ่งชื่อ ScriptMode ซึ่งมี option ให้เลือก 4 ข้อ คือ Auto, Inherit, Debug, Release เพื่อความเข้าใจที่ง่ายขึ้นมาลองทดสอบกันเลยครับ



จากรูปผมสร้าง page ใหม่โดยให้มี ScriptManager แค่ 1 ตัว กำหนด ScriptMode เป็น debug แล้วลองรันทดสอบดูครับ (ถ้าใช้ IE ต้องไปเอา Disable Script Debugging ของ IE ใน Option ออกก่อนนะครับ ถึงจะ debug script ได้)



ลองดูใน Script Document ของ VS จะเห็นว่านอกจาก Default.aspx แล้วยังมี WebResource 1 ไฟล์กับ ScriptResource อีก 2 ไฟล์เพิ่มขึ้นมา ตอนนี้เรามา focus ที่ ScriptResource ครับ ลอง double click มาตัวหนึ่ง จะเห็นว่าข้างในมันคือ javascript นี่เอง มีใส่ comment และ เว้นบรรทัดสวยงามอ่านง่ายครับ สังเกตุชื่อใน comment ครับ ว่ามันคือ MicrosoftAjax.debug.js

คราวนี้ลองเปลี่ยน ScriptMode เป็น Release ดูบ้าง


ลองรันดูครับ


จะสังเกตุว่าไฟล์ที่นำมาทำ ScriptResource จะเปลี่ยนไปเป็น MicrosoftAjax.js แทน ซึ่งมี comment นิดเดียวและก็โค้ดเรียงติดกันเป็นพรืด

โดยปกติเราไม่ค่อยได้ debug javascript พวกนี้อยู่แล้ว ก็สามารถกำหนด ScriptMode เป็น Release เลยก็ได้ครับ เพราะขนาดไฟล์จะเล็กกว่า ไม่กิน bandwidth ครับ

ส่วนถ้าเราเลือก ScriptMode เป็น Auto ตอนที่รันจะขึ้นอยู่กับว่า Web เราเลือก Configuration เป็น debug หรือว่า release ครับ WebServer จะไปเลือกไฟล์ js ที่ตรงกับ config ของเรามาสร้าง ScriptResource ให้

วันอาทิตย์ที่ ๒๑ กุมภาพันธ์ พ.ศ. ๒๕๕๓

ASP.NET สั่งเคลียร์ Session เมื่อเปลี่ยน Page

วันนี้เจอคำถามที่ greatfriends ว่าเมื่อ User ปิด Browser หรือเปลี่ยน Page เราต้องการไปเคลียร์ Session ของ Page เดิมจะทำยังไงดี

ถ้าเป็นเรื่องปิด Browser หรือว่า User ไปเปิดเวบอื่นคงไม่มีปัญหาครับ เพราะ ASP.NET มันจะเคลียร์ค่าให้เมื่อ Session Time Out อยู่แล้ว ซึ่งเราก็สามารถเขียนโค้ดใน Session_End ที่ Global.asax เพิ่มเติมก็ได้ แต่ปัญหาคือถ้า user เปลี่ยนหน้า เราจะทำยังไงดี สิ่งแรกที่ผมคิดคือ เรากำหนดให้มัน Post Back กลับมาหน้าเดิมก่อน เพื่อสั่ง Clear Session จากนั้นเราค่อยสั่ง Navigate ไปยังหน้าที่ต้องการอีกที

เช่นสมมติ เรามี User Control 1 ตัว เป็นเมนูสำหรับ Application เราใช้ <asp: Menu> และสร้าง <asp:MenuItem> เพื่อระบุเมนูย่อย แทนที่เราจะใช้ NavigateUrl Attribute เพื่อสั่ง Redirect ไปหน้าใหม่ทันที่ เราก็มาเขียนโค้ดที่ MenuItemClick Event แทนครับ

พอตอนเย็นก็นึกวิธีใหม่ออก ก็เลยมาลองดูครับ วิธีนี้คือ เราใช้ ASP.NET AJAX มาเรียก WebService เพื่อทำการ Clear Session นั่นเองครับ ลองมาดูโค้ดของ WebService กันก่อน


Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

Namespace jNithi.WS
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class SessionManager
Inherits System.Web.Services.WebService

<Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Function ClearSession(ByVal sessionName As String) As Boolean
Dim session As System.Web.SessionState.HttpSessionState
session = System.Web.HttpContext.Current.Session

If session(sessionName) IsNot Nothing Then
Select Case sessionName.ToUpper
Case "SESSION_RECEIPT_REPORT"
DirectCast(session(sessionName), CrystalDecisions.CrystalReports.Engine.ReportDocument).Dispose()
Case "SESSION_RECEIPT_DATA"
DirectCast(session(sessionName), IList).Clear()
Case Else
End Select
session(sessionName) = Nothing
session.Remove(sessionName)
End If

End Function

End Class

End Namespace


ทีนี้ในหน้า aspx เราก็เขียน javascript สำหรับมาเรียก Webservice ตัวนี้ครับ

<script type="text/javascript">
function Body_OnUnload() {
jNithi.WS.SessionManager.ClearSession('SESSION_RECEIPT_REPORT');
}

</script>
</head>
<body onunload="Body_OnUnload();">
<form id="form1" runat="server">

<asp:ScriptManager ID = "ScriptManager1" runat="server" >
<services>
<asp:ServiceReference Path="~/wsSession.asmx" />
</services>

</asp:ScriptManager>


เท่าที่ลองทดสอบดู ก็ใช้งานได้ผลโอเคนะครับ เมื่อเราเปลี่ยนหน้า หรือปิด Browser มันจะไปเรียก WebService เพื่อสั่ง Clear Session ให้ แต่มีข้อแม้นิดหนึ่งครับ คือ onunload event ของ Body นั้นมันจะทำงานทุกครั้งที่มีการเปลี่ยนหน้า นั่นคือ ถ้ามีการ PostBack กลับไป มันก็จะเกิด Event นี้ด้วยครับ แต่ถ้าเราออกแบบ ASP.NET AJAX Page ของเราดีๆ ไม่ให้มีการ Post Back กลับไป แนวคิดนี้ก็ทำงานได้โอเคครับ

เดี๋ยวคงต้องขอทดสอบอีกซักพัก ก่อนจะเอาไปใช้จริงครับ

วันพุธที่ ๑๙ สิงหาคม พ.ศ. ๒๕๕๒

สร้าง DIV เพื่อบัง WebPage ขณะใช้งาน AJAX

ปกติเวลาพัฒนา Web Application ด้วย ASP.NET ผมมักจะใช้ ASP.NET AJAX ร่วมด้วยเสมอ และเมื่อมีการ PostBack หรือเรียกใช้ WebServices ก็จำเป็นต้องเขียน javascript เพื่อโชว์รูปว่ากำลัง Update และ disable controls ต่างๆ

พอดีได้เข้าไปดูเวบไหนจำไม่ได้แล้วครับ เค้าน่าจะสร้าง Div ที่กำหนด OPACITY ไว้เพื่อให้เป็นกรอบจางๆสำหรับบังหน้าเวบขณะ process งาน ก็สะดวกดีนะครับ เพราะว่าถ้าในหน้ามี control หลายๆตัว จะไปนั่งไล่ disable ทีละตัวก็จะถึกไปหน่อย ยิ่งถ้าใช้พวก asp:menu หรือ Master Page ด้วยแล้ว เสียเวลาน่าดูชม สร้าง Div มาบังมันซะเลย เร็วและได้ผลลัพท์ไม่แตกต่างกัน (อาจจะดีกว่าด้วยครับ) เลยมาลองทำดูบ้างครับ


<div id="divProgress">
<div id="divBackground"style="z-index:999; position:absolute;top:0px;left:0px; background-color:#eeeeee;filter:alpha(opacity=40); opacity:0.4;-moz-opacity:0.4"></div>
<div id="divImg" style="z-index:1000;position:absolute;border: 1px solid #800000; top:340px;left:200px;width:300px;text-align:center;background-color:#FFDECE">
<img alt="Processing" src="../Images/loading.gif" /><asp:label ID="lblLoading" CssClass ="textNormal" Text="Preparing reports..." runat="server"></asp:label>
</div>
<div>


โดยปกติก็จะกำหนด visibility เป็น hidden ไว้ก่อน พอมีการเรียกใช้ AJAX ก็จะเปลี่ยนเป็น visible มาดูโค้ดกันครับ


<script type="text/javascript" id="MSAJAX">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(onBeginRequest);
prm.add_endRequest(onEndRequest);

function onBeginRequest(sender, e) {
ShowProgress(true);
}

function onEndRequest(sender, e) {
ShowProgress(false);
}
function ShowProgress(isShow) {
if(isShow == true){
$get("divProgress").style.visibility = "visible";
var dv = $get("divBackground")
dv.style.width = "1200px";
dv.style.height = "1000px";
}else{
$get("divProgress").style.visibility = "hidden";
}
}
</script>


เนื่องจากผมใช้ PageRequestManager ของ ASP.NET AJAX เป็นตัวสั่ง ShowProgress ดังนั้น Script นี้ต้องวางไว้ข้างล่าง ScriptManager control นะครับ

วันเสาร์ที่ ๑ สิงหาคม พ.ศ. ๒๕๕๒

jQuery กับการกำหนด Mouse Hover ใน GridView

อ้างอิงจากคำถามที่ GreatFriends ครับ
ขอคำแนะนำเรื่อง GridView กับ Jquey จ้า
http://greatfriends.biz?110946

เจ้าของกระทู้ต้องการทำ Highlight สีของแถวใน GridView เมื่อเอา mouse ไปชี้ที่แถวนั้นๆครับ และพอกด Select ใน GridView ก็ให้นำข้อมูลมาใส่ textbox

จริงๆแล้วถ้าข้อมูลที่จะใส่ TextBox อยู่ใน GridView ทั้งหมด เราสามารถใช้ jQuery ดึงข้อมูลของแถวมาใช้ได้เลย แต่ผมสมมติว่าเราต้องการข้อมูลอื่นๆ โดยอ้างจาก Id ของข้อมูลที่เลือกละกันครับ ดังนั้นผมก็ต้อง Post back กลับไปเพื่อหาค่ามาใส่ใน textbox ก็เลยทำหน้า page มาลองทดสอบดูครับ

โค้ดส่วน Head ครับ Style ผม copy มาจากเจ้าของกระทู้เลย ส่วน jQuery ผมใช้ที่อาจารย์สุเทพแก้ไขให้ นำมาแยกออกจาก $document.ready() เป็น LoadHandle function ครับ

<head runat="server">
<title>Test</title>
<style>
.trMouseClick {
background-color: Transparent;
color: #A4D1A1 !important;
text-decoration: none;
}

.trMouseOver {
background-color: #F2FEF2 !important;
color: #A4D1A1 !important;
text-decoration: none;
}

.trMouseOver a {
background-color: #F2FEF2 !important;
color: #A4D1A1 !important;
}
</style>
<script type="text/javascript" src="../Scripts/jquery-1.3.2-vsdoc.js"></script>
<script type="text/jscript">

$(document).ready(LoadHandle);

function LoadHandle() {
$("tr:gt{0}").hover(function() {
$(this).addClass("trMouseOver");
}, function() {
$(this).removeClass("trMouseOver");
});
$("tr:gt{0}").click(function() {
$(this).addClass("trMouseClick").siblings().removeClass("trMouseClick");
});
}

</script>
</head>


โค้ดส่วน Form tag (ใน Body)

<asp:ScriptManager ID="ScriptManager1" runat="server">:
</asp:ScriptManager>:
<div id = "main" style="height:700px;z-index:-10">:
<div id="text" style="position:absolute">:
<asp:UpdatePanel ID ="UpdatePanel1" runat="server" UpdateMode="Conditional" RenderMode="Block">:
<ContentTemplate>:
<div id="Update" style="position:absolute;top:50px; width:700px">:
<asp:GridView ID="gvInvoice" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BorderColor="Gainsboro" BorderStyle="None"
BorderWidth="1px" CellPadding="0" GridLines="Horizontal"
AutoGenerateSelectButton="True" DataKeyNames="ItemId">:
<Columns>:
<asp:TemplateField SortExpression="ITEMID">:
<ItemStyle Width="0px">:</ItemStyle>:
<ItemTemplate>:
<asp:HiddenField id="hdnRecId" runat="server" Value='<%# Bind("ITEMID") %>:'>:</asp:HiddenField>:
</ItemTemplate>:
</asp:TemplateField>:
<asp:TemplateField HeaderText="Item No">:
<HeaderStyle Width="40px" HorizontalAlign="center">:</HeaderStyle>:
<ItemStyle HorizontalAlign="center" />:
<ItemTemplate>:
<asp:Label id="lblItemNo" runat="server" Text='<%# Eval("ORDERNO") %>:' >:</asp:Label>:
</ItemTemplate>:
</asp:TemplateField>:
<asp:TemplateField HeaderText="Invoice Date">:
<ItemStyle Width="100px">:</ItemStyle>:
<HeaderStyle HorizontalAlign="Center">:</HeaderStyle>:
<ItemTemplate>:
<asp:Label style="TEXT-ALIGN: center" id="Label2" runat="server" Width="80px" Text='<%# Bind("InvoiceDate", "{0:dd/MM/yyyy}") %>:'>:</asp:Label>:
</ItemTemplate>:
</asp:TemplateField>:
<asp:TemplateField HeaderText="Product Code">:
<ItemStyle Width="60px">:</ItemStyle>:
<HeaderStyle HorizontalAlign="Center">:</HeaderStyle>:
<ItemTemplate>:
<asp:Label style="TEXT-ALIGN: center" id="Label3" runat="server" Width="50px" Text='<%# Bind("ProductCode") %>:'>:</asp:Label>:
</ItemTemplate>:
</asp:TemplateField>:
<asp:TemplateField HeaderText="Amount (THB)">:
<ItemStyle Width="80px">:</ItemStyle>:
<HeaderStyle HorizontalAlign="Center">:</HeaderStyle>:
<ItemTemplate>:
<asp:Label style="TEXT-ALIGN: right" id="Label5" runat="server" Width="70px" Text='<%# Bind("Amount","{0:#,##0.00}") %>:'>:</asp:Label>:
</ItemTemplate>:
</asp:TemplateField>:
<asp:TemplateField ShowHeader="False">:
<ItemStyle Width="40px">:</ItemStyle>:
<ItemTemplate>:
<asp:ImageButton ID="btnEdit" runat="server" CommandName="Select" ImageUrl="~/Images/icon_edit.gif" ToolTip="Edit" />:
</ItemTemplate>:
</asp:TemplateField>:
</Columns>:
<RowStyle >:</RowStyle>:
<SelectedRowStyle>:</SelectedRowStyle>:
<PagerStyle HorizontalAlign="Right" VerticalAlign="Top">:</PagerStyle>:
<HeaderStyle >:</HeaderStyle>:
<AlternatingRowStyle >:</AlternatingRowStyle>:
</asp:GridView>:
</div>:
<div id="dvContent" style="position:absolute;top:400px">:
<asp:TextBox ID="txtId" runat="server" style="width:100px" MaxLength="6">:</asp:TextBox>:
<asp:TextBox ID="txtDescription" runat="server" style="width:250px">:</asp:TextBox>:
<asp:TextBox ID="txtAmount" runat="server" style="width:250px">:</asp:TextBox>:
</div>:
</ContentTemplate>:
</asp:UpdatePanel>:
</div>:
</div>:


โค้ดส่วน Code Behind ครับ

Imports jnithi.Class.Invoice

Partial Class InvoiceTest
Inherits System.Web.UI.Page
#Region "Local fields"

Private _inv As List(Of Entity.Invoice) = Nothing

#End Region

Private Sub GetInvoiceByInvoiceNo()
If _inv IsNot Nothing Then
_inv.Clear()
_inv = Nothing
End If
_inv = Manager.Invoice.GetInvoiceByInvoiceNo("Test1")
Session("Invoice") = _inv
End Sub

Private Sub BindGridView()
gvInvoice.DataSource = _inv
gvInvoice.DataBind()
End Sub

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load

If Not IsPostBack Then
GetInvoiceByInvoiceNo()
Else
_inv = Session("Invoice")
End If
BindGridView()
End Sub

Protected Sub gvInvoice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvInvoice.SelectedIndexChanged
Dim id As Integer = CType(gvInvoice.SelectedValue, Integer)
Dim item As Entity.Invoice = _inv.Find(Function(i) i.ItemID = id)
Me.txtId.Text = id
Me.txtDescription.Text = item.ItemWorkDesc
Me.txtAmount.Text = item.LCCost.ToString("#,##0.00")
ScriptManager.RegisterStartupScript(Page, Page.GetType, "GVDataBound", "LoadHandle();", True)
End Sub


ผลการทดสอบครับ


สรุป
1. ผมแยก LoadHandle Function ออกมาจาก $document.ready() เพื่อที่ว่าให้ function นี้เป็น Event Handler เมื่อทำการ Load ข้อมูลฝั่ง client เสร็จครับ
2. ใน GridView_SelectedIndexChanged ผมทำการ register script เพื่อให้เรียก LoadHandle functionให้ทำงาน เมื่อ UpdatePanel ทำการ Update ข้อมูลเสร็จแล้ว
3. ถ้าไม่ใช้ ScriptManager.RegisterStartupScript ซึ่งเป็นการสั่งที่ฝั่ง Server เราสามารถใช้ PageRequestManager (เขียน javascript) แทนได้ครับ

วันพุธที่ ๑๕ กรกฎาคม พ.ศ. ๒๕๕๒

jQuery ทำ highlight ขัอมูลใน GridView

ผมเคยทำโปรแกรมค้นหาข้อมูลจากไฟล์เอกสารที่เก็บไว้ใน File Server โดย user สามารถใส่ key word ได้หลายตัว จากนั้นโปรแกรมจะไปค้นหาว่ามีไฟล์ไหนบ้างที่มีคำหรือประโยคตรงกับเงื่อนไขที่ต้องการ แล้วนำข้อมูลรวมถึง url มาใส่ใน GridView
ทีนี้ user ก็ต้องการให้โปรแกรมสามารถ highlight คำหรือประโยคใน GridView ที่ตรงกับ key word ด้วย ซึ่งก่อนหน้านี้ผมก็เขียน javascript วนลูปเพื่อทำ highlight ซึ่งโค้ดก็ยาวพอสมควร วันนี้จะลองมา modify โดยใช้ jQuery มาช่วยครับ โดยผมจะเพิ่ม Custom Attribute ให้กับ Control ที่ต้องการจะไปทำ highlight ครับ ซึ่งในแต่ละแถวของ GridView จะให้ไป highlight ที่ label 2 ตัว

<asp:TemplateField HeaderText="Title" HeaderStyle-Width="400px" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblDocTitle" runat="server" ForeColor="Blue" style="font-size: 10pt" Highlight="true" Font-Bold="False"><%# eval("DocTitle") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Abstract" HeaderStyle-Width="300px" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblAbstract" runat="server" Highlight="true" ><%# eval("Abstract") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>

เนื่องจากผมใช้ ScriptManager และ UpdatePanel ด้วย จากบทความเก่าผมใช้วิธีเขียนคำสั่ง jQuery ที่ code behind แล้วสั่ง ScriptManager ให้ Register Script ให้ ตามตำราเรียกวิธีนี้ว่าเป็น Server-centric แต่คราวนี้เราจะมาลองทำ Client-centric ดูบ้าง แทนที่เราจะใช้ UpdateProgress Control ผมก็จะมาใช้ PageRequestManager ในการแสดงรูปภาพแทน รวมถึงทำการ register event handler function ครับ

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<script type="text/javascript" id="MSAjax">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beginRequest);
prm.add_pageLoaded(pageLoaded);

function beginRequest(sender, args) {
$("#divProgress").show();
$("#MainGridView").html("");
}

function pageLoaded(sender, args) {
//Add elements'event handler.
$("txtFreeText").keypress(function(e) { txtFreeText_OnKeyPress(e); });
$("btnSearch").click(function() { ValidateSearch(); });
$("#divProgress").hide();

HighlightSearch();
}
</script>

คราวนี้มาลองดูโค้ดที่สำหรับทำ Highlight กันครับ

<style type="text/css">
.highlight{font-weight: bold; font-size: 16px; color: blue; background-color: papayawhip};
</style>
<script type="text/javascript" src="Scripts/jquery-1.3.2-vsdoc.js"></script>

  
<script type ="text/javascript" id="MainScript">

function trim(str) {
return str.replace(/^\s*|\s*$/g, "");
}

function HighlightSearch(){
var strSearch = $("#txtFreeText").val();
if (trim(strSearch)=="") return false;

strSearch = strSearch.replace(/\"/gi,"");
strSearch = strSearch.replace(/\s*and\s*/gi, " ");
strSearch = strSearch.replace(/\s*or\s*/gi," ");
var arrSearch = strSearch.split(" ");

$("[Highlight=true]").each(function() {
var elm = $(this);
var strAbstarct = elm.html();
for (var i = 0; i < arrSearch.length; i++) {
var RE = new RegExp(arrSearch[i], "gi");
strAbstarct = strAbstarct.replace(RE, "<span class='highlight'>" + arrSearch[i] + "</span>");
}
elm.html(strAbstarct)
});
}

</script>

จากโค้ดด้านบน ผมใช้ Attribute Selector ในการเลือก element ที้ต้องการทำ Highlight มาจากนั้นมาวนลูปด้วย jQuery.each() ครับ แล้วก็ไปแก้ไข้ html ของ element ให้เพิ่ม span เพิ่อทำ highlight คำที่ต้องการ ลองรันดูได้ผลลัพธ์ตามต้องการครับ