星期日, 11月 29, 2009

[Asp.net] 在content page擷取master page的事件

在content page 新建master page 控制項事件(這範例是button),原文內以下內容需注意:

TypeName:為主版頁面指定類型名稱。
VirtualPath:指定產生強型別之檔案的路徑。 
ps:如果同時定義了 TypeNameVirtualPath 兩個屬性,則 @ MasterType 指示詞將失敗。

Reference:
Capture Master Page Events in Content Pages - ASP.NET 2.0
@ MasterType 指示詞

星期五, 11月 27, 2009

asp.net 使用多個以上的sitemap

由於使用sitemap可以快速建立menu選單,
又可以加上securityTrimmingEnabled="true"來依成員角色顯示不同的選單,
但是用了這個安全機制又會讓網站的選單空空的,
所以就不加上這個屬性,
改用二個sitemap檔案來自動切換(二個sitemap的節點數不一樣)

以下是web.config

<!--
sitemap角色權限讀取 securityTrimmingEnabled="true"
-->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>

<add name="XmlSiteMapProvider" description="未登入與登入"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="common-map.sitemap" securityTrimmingEnabled="false" />

<add name=";XmlSiteMapProviderForAdmin" description="登入管理員"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="admin-map.sitemap" securityTrimmingEnabled="false" />

</providers>
</siteMap>


由於管理者與未登入及登入會員的頁面都是使用不同的master page,
於是就新增一個繼承System.Web.UI.MasterPage的 BaseMaster物件

///
/// BaseMaster 的摘要描述
///

public class BaseMaster : System.Web.UI.MasterPage
{
public BaseMaster()
{
//
// TODO: 在此加入建構函式的程式碼
//
}
///
/// 切換不同的sitemap
///

///
///
public string SitemapHelper(string username)
{
string provider = "XmlSiteMapProvider";
string[] roleTmp = System.Web.Security.Roles.GetRolesForUser(username);
for (int i = 0; i < roleTmp.Length; i++)
{
if (roleTmp[i] == "Admin")
{
provider = "XmlSiteMapProviderForAdmin";
break;
}
}
return provider;
}
}


接著在網站內master加入以下code,
透過 this.SiteMapDataSource1.SiteMapProvider切換不同的SiteMapProvider

public partial class guest_mp : BaseMaster
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.User.Identity.IsAuthenticated)
{
if (!IsPostBack)
{
this.SiteMapDataSource1.SiteMapProvider = this.SitemapHelper(this.Page.User.Identity.Name);
}
}
}
}

星期一, 11月 23, 2009

C# WebClient Post

使用webclient來做post,
很方便使用。
要能正確取得post的結果,
就要看各個網站的驗證的方法如何了。
方法如下:
System.Net.WebClient wc = new System.Net.WebClient();

string url = "http://www.thsrc.com.tw/tc/ticket/tic_time_result.asp";
string postData = "rom=1&to=5&sDate=2009%2F11%2F23&TimeTable=21%3A00&FromOrDest=From&x=33&y=10";

wc.Encoding = Encoding.UTF8;

byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());

wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-TW; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5");
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Referer", "http://www.thsrc.com.tw/tc/index.asp");

byte[] recData = wc.UploadData(url, "POST", sendData);
string tmp = Encoding.UTF8.GetString(recData);



如果又要讓Session能夠保存的話,
可參考這篇的做法:
C# 實現Webclient保持Session的方法

Shell.Applicatio Using C#

1,直接添加引用 %windir%\system32\Shell32.dll
Shell32.ShellClass sc = new Shell32.ShellClass();
sc.FileRun();
2,不用添加任何引用直接用反射 C#
//通过 ProgID 取得 com 对象类型
Type tShell =Type.GetTypeFromProgID("Shell.Application");
//实列对象
object oShell = Activator.CreateInstance(tShell);
//反射调用
tShell.InvokeMember("FileRun"
, BindingFlags.InvokeMethod | BindingFlags.Default
, null
, oShell
, null //如果有参数在这里 new object[]{参数一,参数二,参数三,....}
);

//释放对象
System.Runtime.InteropServices.Marshal.ReleaseComObject(oShell);

上面二個方式都可以實作,
不過比較起來的話,第一種的方法比較容易撰寫,
瞬間跟CCN大師請教一下就有了結果,
不過是神之手,不過還是記錄一下,避免忘記
以下是利用shell32控制網路連線自動連線方法,
不過只適用32位元以及繁體中文os,自已用的小工具就不考慮太多了XD,
用個timer就可以一直監控了!!
PS:記得加入參考  COM->Microsoft Shell Controls And Automation(SHELL32.dll)
/// <summary>
/// 保持連線
/// </summary>
/// <param name="connectionName">連線的裝置名稱</param>
void KeepConnection(string connectionName)
{
Shell32.ShellClass shell = new ShellClass();
//列出namespace代碼
//for (int i = 0; i < 100; i++)
//{
//    if (shell.NameSpace(i) != null)
//        this.listBox1.Items.Add("[" + i.ToString() + "]" + shell.NameSpace(i).Title);
//}

Folder applicationObj = shell.NameSpace(3);
//取得控制台清單
foreach (FolderItem fItem in applicationObj.Items())
{
//this.listBox1.Items.Add(fItem.Name);
if (fItem.Name == "網路連線")
{
if (fItem.IsFolder)
{
//這裡的轉換要注意一下
Folder network = (Folder)fItem.GetFolder;
//取得網路連線清單
foreach (FolderItem fItem2 in network.Items())
{
//this.listBox1.Items.Add(fItem2.Name);
if (fItem2.Name == connectionName)
{
//列出該項目右鍵選單
foreach (FolderItemVerb fivb in fItem2.Verbs())
{
//this.listBox1.Items.Add(fivb.Name);
if (fivb.Name.IndexOf("連線") > -1 && fivb.Name.IndexOf("預設") == -1 && fivb.Name.IndexOf("中斷") == -1)
fivb.DoIt();
}
}
}

}

}
}
}



以下是G大神提供的資料~
Reference:
C#调用dll文件中的函数的问题
minimizes all windows..
[VB.NET/ C#.Net / VC++.Net] 如何由程式開啟 IE 並進行會員登入
[C#][VB.NET]顯示桌面
C#怎么实现启用和禁用本地网卡?

星期日, 11月 22, 2009

remote debugger using vs 2008

Remote Debug in VS.NET 2008

Remote IIS Debugging : Debug your ASP.NET Application which is hosted on "Remote IIS Server"

asp.net using memcache

安裝Memcache
Step1:下載Memcache (memcached for Win32)
Step2:安裝與啟動Memcache
sc create memcached binPath= "C:\memcached-1.2.1-win32\memcached.exe -p 8888 -l 127.0.0.1 -m 512 -d runservice" DisplayName= "memcached server" start= auto depend= TCPIP
相關參數:

Asp.net設定
1.將取得的MemCache用戶端(download)解壓縮內的三個dll加入參考Enyim.Caching.dll, log4net.dll, MemcachedProviders.dll
2.設定web.config內的configsection加入以下tags
在web.config或app.config裡的<configSections>區塊加入下列設定:

<section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders"
allowDefinition="MachineToApplication" restartOnExternalChanges="true"/>
<sectionGroup name="enyim.com">
<section name="memcached"
type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/>
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>


3.然後在configuration區塊裡加入下面的詳細設定
<!--Memcatch 詳細設定-->
  <cacheProvider defaultProvider="MemcachedCacheProvider">
    <providers>
      <add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders"
      keySuffix="_MySuffix_" defaultExpireTime="2000"/>
    </providers>
  </cacheProvider>

  <enyim.com>
    <memcached>
      <servers>
        <!--Memcatch default port 11211-->
        <add address="127.0.0.1" port="8888" />
      </servers>
      <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
    </memcached>
  </enyim.com>

  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}]- %message%newline" />
      </layout>
    </appender>
    <root>
      <priority value="WARN"/>
      <appender-ref ref="ConsoleAppender">
        <filter type="log4net.Filter.LevelRangeFilter">
          <levelMin value="WARN"/>
          <levelMax value="FATAL"/>
        </filter>
      </appender-ref>
    </root>
  </log4net>


*.aspx 範例
        DataTable dt = (DataTable)MemcachedProviders.Cache.DistCache.Get("SearchKey3");
        if (dt == null)
        {
            Response.Write("without cache");
            Module_Command.GetMenuList obj = new Module_Command.GetMenuList(3);
            dt = (System.Data.DataTable)obj.Execute();
            MemcachedProviders.Cache.DistCache.Add("SearchKey3", dt, TimeSpan.FromSeconds(5));
        }
        this.GridView1.DataSource = dt;
        this.GridView1.DataBind();



檢查物件是否有存在memcache

Telnet 到你的伺服器(ex:telnet 127.0.0.1 ),輸入指令'stats',就可以看到目前memcached的狀態。
curr_items 是目前memcached裡暫存物件的數量。

Reference:
在.NET應用程式裡使用memcached暫存Linq資料
MSDNDataContractSerializer Class
如何用 C# 撰寫序列化(Serialize)與反序列化(Deserialize)
用 C# 撰寫序列化(Serialize)與反序列化(Deserialize) - Part 2
.NET 筆記:序列化

星期三, 11月 18, 2009

jquery get tagname

今天剛好需要retrieve element,
要判斷某一元素時,該元素剛好沒有其他屬性,
只剩tagname可以使用XD,
所以以下是利用jquery取得取得元素的tagname。
回傳的tagName是"大寫"

$(chirdObj).parent().attr("tagName") == "UL"

星期一, 11月 16, 2009

c# 日期運算 timespan

string lateTime = this.itemsAgent.GetLateTestLog(this.UserID);
DateTime lateDT = DateTime.Parse(lateTime);
//string currentTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
//日期相減
TimeSpan ts = DateTime.Now.Subtract(lateDT);
int subMin = ts.Minutes;
//日期比較
//DateTime.Compare(t1,t2),回傳一個整數小於0,则t1小於t2,大於0,则t1大於t2, =0,则t1=t2
int compareVal = DateTime.Compare(t1, t2) ;

div 內圖片置中(相簿封面效果)

每個網站常用到的div照片封面置中的方法,
我的每張thumb為100*100大小內的等比例縮圖。
所以最外圍的div.albumCover設定110*110大小,
就可以很漂亮的顯示了!!。
#listDiv
{
width:100%;
background:#fff;
padding:10px;
}


#listDiv:after
{
content: ".";
display: block;
clear: both;
height: 0;
overflow: hidden;
visibility: hidden;
}

#listDiv ol li
{
display: inline;
float: left;
text-align: center;
margin-right: 15px;
margin-bottom: 10px;
overflow: hidden;
background-color:#FFFFFF;
}

#listDiv ol li a
{

}

#listDiv ol li a:hover
{

}

/*album title desc*/
#listDiv ol li a span.albumTitle
{
font-size : 12px;
display: block;
text-align: left;
padding-left: 3px;
padding-top: 3px;
padding-bottom: 3px;
}

/*album cover*/
#listDiv ol li div.albumCover
{
display: table-cell;
border:1px solid #CCCCCC;
width:110px;
height:110px;
vertical-align:middle;
text-align:center;
}

#listDiv ol li div.albumCover:hover
{
background-color:#B0C4DE;
}




<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>相簿標題:<asp:Label ID="lblAlbumTitle" runat="server"></asp:Label></h2>
<div id="photoList">
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSourcePhotoList" >
<EmptyDataTemplate>
<div class="icon-yellow">Sorry 目前相簿無照片</div>
</EmptyDataTemplate>
<ItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%-- <img src="photo/default.gif" />--%>
</div>
</a>
</li>
</ItemTemplate>
<AlternatingItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%--<img src="photo/default.gif" />--%>
</div>
</a>
</li>
</AlternatingItemTemplate>
<LayoutTemplate>
<div id="listDiv">
<ol>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ol>
</div>
<div class="Pagination">
<asp:DataPager ID="_moviesGridDataPager" runat="server" PageSize="20">
<Fields>
<asp:NumericPagerField CurrentPageLabelCssClass="pagerlabel" NextPageText="..."
NextPreviousButtonCssClass="pagerlink" NumericButtonCssClass="pagerlink"
PreviousPageText="..."/>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourcePhotoList" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT ActivityAlbumTitle,ActivityPhotoID, ActivityPhotoAID, ActivityPhotoFile,ActivityAlbumDirectory FROM vw_ActivityPhotoList
Where ActivityPhotoAID=@aid">
<SelectParameters>
<asp:QueryStringParameter Name="aid" QueryStringField="aid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSourceGetAlbumTitle" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT [ActivityAlbumTitle] FROM [ActivityAlbum] WHERE ([ActivityAlbumID] = @ActivityAlbumID)">
<SelectParameters>
<asp:QueryStringParameter Name="ActivityAlbumID" QueryStringField="aid"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</asp:Content>

Treeview 蒐集

Treeview 蒐集

Reference:
Context Menu on TreeView
ASP.NET 2.0 使用資料表動態產生TreeView的樹狀結構
Graphic JavaScript Tree with Layout
[asp.net] 簡單秀Treeview, 使用 jQuery
Building Trees from Lists in .NET
PS:Printing Out All Nodes using Nested HTML ul and li Tags
Hierarchical Treeview with ASP.NET MVC & jQuery

Jquery plugin : Uploadify 多檔上傳

好用的多檔上傳元件,
伺服端語言可用asp.net或php,
以下範例是一個將相片上傳至相本的的動作~
更多說明請參考網站文件
http://www.uploadify.com/

 <!--uploader-->
<script type="text/javascript" src="../js/swfobject.js"></script>
<script type="text/javascript" src="../js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/uploadify.css"/>
//限制上傳的檔案格式一定要指定fileDesc
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
"uploader": "../js/uploadify.swf",
"script": "../uploadHandler.ashx",
"cancelImg": "../images/cancel.png",
"sizeLimit": 1024000,
"queueID": "fileQueue",
"auto": false,
"fileDesc":"選取上傳的照片",
"fileExt": "*jpeg;*.jpg;*.gif;*.png",
"multi": true,
"onComplete": function(event, queueID, fileObj, response, data) {
if (response == "0")
alert("上傳發生錯誤");
else {
$("#uploadSet").append("<div id=\"fileitem\" >file:" + fileObj.name + " size:" + fileObj.size + "</div>");
}
}
});
});

function Upload() {
$("#uploadSet").html("");
$("#uploadify").uploadifySettings("scriptData", { "aid": $("#ctl00_ContentPlaceHolder1_hiddenAlbum").val() });
$("#uploadify").uploadifyUpload();
}

function CancelUpload() {
$("#uploadify").uploadifyClearQueue();
}

</script>


需注意的是:.net預設的上傳大小為上限值 4096 (4 MB)
因此會產生超出最大要求長度的exception
要再webconfig加入以下設定
例如, Web.config 設定會允許最大 10 MB 的檔案上傳(設跟uploadifyg sizeLimit一樣大):
<System.Web>
<httpRuntime maxRequestLength="10240" />
</System.Web>

*.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>照片上傳</h2>
<p class="help">請上傳小於 1MB 的圖片,僅支援.jpg、.gif、.png等圖片格式</p>
<p>支援多檔上傳</p>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />

&nbsp;&nbsp;<a href="javascript:Upload()" runat="server">上傳圖片</a>
&nbsp;&nbsp;<a href="javascript:CancelUpload()" >取消選取圖片</a>

<input id="hiddenAlbum" type="hidden" runat="server" />
<div id="uploadSet"></div>
</asp:Content>


uploadHandler.ashx接收上傳的檔案

<%@ WebHandler Language="C#" Class="uploadHandler" %>

using System;
using System.Web;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BigdControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public class uploadHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

if (context.Request["aid"] == null)
{
context.Response.Write("0");
return;
}

//uploadifySettings post 的 album id
string aid = context.Request["aid"].ToString();

//album directory
string aDirectory = this.GetAlbumDirectory(aid);
if (String.IsNullOrEmpty(aDirectory))
return;//無相簿目錄

string fullFileName = context.Server.MapPath("Album/" + aDirectory + "/");
string fullFileNameThumb = context.Server.MapPath("Album/" + aDirectory + "/thumb/");

for (int i = 0; i < context.Request.Files.Count; i++)
{
HttpPostedFile postedFile = context.Request.Files[i];

string fileFormat = Path.GetExtension(postedFile.FileName);
if (ModuleSecurity.ModuleSecurity.FileChecker(fileFormat,new string[] { ".jpg", ".gif", ".png" }))
{
string orgFileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
//string fileName = orgFileName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
Random rn = new Random((int)DateTime.Now.Ticks);
string fileName = rn.Next().ToString() + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;

fullFileName = fullFileName + fileName;
fullFileNameThumb = fullFileNameThumb + fileName;

//save photo
postedFile.SaveAs(fullFileName);

//縮圖
postedFile.SaveAs(fullFileNameThumb);
ImageProcessing.Save(fullFileNameThumb,
ImageProcessing.ImagePreviewThumb(fullFileNameThumb, 100, 100, Color.White, InterpolationMode.High, SmoothingMode.HighQuality));

//add photo
this.AddAlbumPhoto(aid, fileName);
}
}

context.Response.Write("1");
}

public bool IsReusable {
get {
return false;
}
}


/// <summary>
/// 取得相簿目錄
/// </summary>
/// <param name="aid">相簿id</param>
/// <returns></returns>
public string GetAlbumDirectory(string aid)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("select ActivityAlbumDirectory from ActivityAlbum where ActivityAlbumID=@aid",sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
string direcdtory = sqlCmd.ExecuteScalar().ToString();
sqlConn.Close();

return direcdtory;
}

/// <summary>
/// 新增相片
/// </summary>
/// <param name="aid">相簿id</param>
/// <param name="photo">相本檔名</param>
public void AddAlbumPhoto(string aid, string photo)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("insert into ActivityPhoto(ActivityPhotoAID,ActivityPhotoFile)values(@aid,@photo) ", sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
sqlCmd.Parameters.Add("photo", SqlDbType.NVarChar).Value = photo;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}

}

星期日, 11月 15, 2009

[jQuery plugin] Validator addMethod Func

由於預設的Validator裡面的驗證欄位的方法可能不夠我們使用,
所以可以透過addMethod來自訂我們的驗證規格,
剛好用到記錄一下。
jQuery.validator.addMethod("projSN", function(value, element) {
var length = value.length;
return this.optional(element) || (length == 5 && /^[A-Z]{5}$/.test(value));
}, "專案代碼僅限英文大寫五碼");

jQuery.validator.addMethod("number", function(value, element) {
var length = value.length;
return this.optional(element) || (/^[1-9]{1}[0-9]*$/.test(value));
}, "欄位只能為數字,且第一位數不能為 0");
//        


Reference:
客户端驗證的極品--jQuery.validator
利用 jQuery.Validate 驗證中華民國身份證字號

星期三, 11月 11, 2009

jQuery plugin : Validation in ASP.NET Master Pages

剛好要在asp.net master page 下使用jquery validation plugin來做欄位驗證,
但我的button又是使用ajax的方式,
是不能將表單產生sumbit的動作Orz,
所以有了以下的解決方法:

頁面上配置鈕
<input id="btnProdcut" type="button" value="送出" runat="server" onclick="MySubmit()"/>
首先先初始化驗證控制項
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
event:"keyup",
rules: {
<%=tbDesignName.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true
},
<%=tbDesignNameEnglish.UniqueID %>: {             
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDesc.UniqueID %>: {             
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDescEnglish.UniqueID %>: {             
minlength: 2,
maxlength:50,
required: true,
}

},
messages: {
<%=tbDesignName.UniqueID %>: {
required: "設計名稱尚未填寫",
minlength: "設計名稱最小長度為 2",
maxlength: "設計名稱最大長度為 10"
},


<%=tbDesignDesc.UniqueID %>: {             
required: "設計描述尚未填寫",
minlength: "設計描述最小長度為 2",
maxlength: "設計描述最大長度為 10"
}
}
});
});
</script>


按鈕執行的鈕
function MySubmit() {
CancelSumbit();
if (FormValidate()) {
if (FileValidate()) {
//驗證成功
else {
//驗證失敗
}
});
}
else
alert("驗證失敗");

}

改由檢查錯誤訊息元素的css屬性 display:none確認驗證是否成功,
function FormValidate() {
var displayChecker = false;
//找出class=error的錯誤訊息元素
$("td .error").each(function(i, obj) {
//alert($(this).css("display"));
if ($(this).css("display") == "none")
displayChecker = true;//表示欄位都通過驗證
else
displayChecker = false;

});

if (displayChecker == true)
return true;
else
return false;
}

摸擬submit的動作來檢查欄位
function CancelSumbit() {
$("input:[type=submit]").submit();
return false;
}

星期二, 11月 10, 2009

Asp.net FindControl

以前沒用FindControl時都習慣把元素的id全列出來

int allControl = this.ListView1.Items[e.ItemIndex].Controls.Count;
for (int i = 0; i < allControl; i++)
{
this.Response.Write(this.ListView1.Items[e.ItemIndex].Controls[i].ClientID + "<br/>");
}


然後就可以找出欲取得值的控制項位置

this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumID"].DefaultValue = ((ImageButton)this.ListView1.Items[e.ItemIndex].Controls[1]).CommandArgument;


由於上面的方法會因控制項往後的位置變更又需要修改程式碼,
非常不好,所以改用FindControl(元素的id)是比較適合的
  this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumTitle"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumTitle")).Text;
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumDesc"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumDesc")).Text;

星期日, 11月 08, 2009

Jquery Plugin: Star Rating

jQuery Star Rating Plugin

Star Rating widget(目前使用,直接有大顆星星的樣式表)

demo6 code
// Create stars
   $("#rat").stars({
    // starWidth: 28, // only needed in "split" mode
    cancelShow: false,
    callback: function(ui, type, value)
    {
     // Hide Stars while AJAX connection is active
     $("#rat").hide();
     $("#loader").show();
     // Send request to the server using POST method
     /* NOTE: 
      The same PHP script is used for the FORM submission when Javascript is not available.
      The only difference in script execution is the returned value. 
      For AJAX call we expect an JSON object to be returned. 
      The JSON object contains additional data we can use to update other elements on the page.
      To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set.
      (see: demo6.php)
     */ 
     $.post("demo6.php", {rate: value}, function(db)
     {
      // Select stars to match "Average" value
      ui.select(Math.round(db.avg));
      
      // Update other text controls...
      $("#avg").text(db.avg);
      $("#votes").text(db.votes);
      
      // Show Stars
      $("#loader").hide();
      $("#rat").show();

     }, "json");
    }
   });

其他你感興趣的文章

Related Posts with Thumbnails