Ajax使用心得

1、先在程序load的时候注册类到Ajax

如:private void Page_Load(object sender, EventArgs e) 
  { 

        Ajax.Utility.RegisterTypeForAjax(typeof(BD0047));        //将类BD0047加到Ajax中

}

2、在要在前调用的方法前加 [AjaxMethod()]
如:[AjaxMethod()]
  public int CountIssueDays(string strIssueDate,string strMaturityDate)
  { 
   int retValue=0;
   if(strIssueDate!="" && strMaturityDate!="")
   {  
    string []strStartDate=new string[]{""};
    string []strEndDate=new string[]{""};
    //将日期分割成数组
    int placeIssueDate=strIssueDate.IndexOf("-",0,strIssueDate.Length);           //判断日期中是否有'-'号
    int placeMaturityDate=strMaturityDate.IndexOf("-",0,strMaturityDate.Length);  //判断日期中是否有'-'号
    if(placeIssueDate==0)
    {
     strStartDate=new string[]{strIssueDate.Substring(0,4),strIssueDate.Substring(4,2),strIssueDate.Substring(6,2)};
           
    }
    else
    {
     strStartDate=strIssueDate.Split('-');
    }
    if(placeMaturityDate==0)
    {
     strEndDate=new string[]{strMaturityDate.Substring(0,4),strMaturityDate.Substring(4,2),strMaturityDate.Substring(6,2)};
    }
    else
    {
     strEndDate=strMaturityDate.Split('-');
    }
               
    TimeSpan tsIssueDays=new TimeSpan();
 
    DateTime dtIssueDate=new DateTime(int.Parse(strStartDate[0]),int.Parse(strStartDate[1]),int.Parse(strStartDate[2]));
    DateTime dtMaturityDate=new DateTime(int.Parse(strEndDate[0]),int.Parse(strEndDate[1]),int.Parse(strEndDate[2]));

    tsIssueDays=dtMaturityDate-dtIssueDate;
                
    retValue=tsIssueDays.Days + 1;
   }
   return retValue;
  }

3、在HTML代码的最底部</Body>前加入JavaScript

var strIssueDays = document.getElementById("txtIssueDays_txtIssueDays_EditBox"); //发行天数

var strMaturityDate = document.getElementById("txtMaturityDate_txtMaturityDate_EditBox"); //到期日

var strIssueDate = document.getElementById("txtIssueDate_txtIssueDate_EditBox"); //发行日

获得页面上的控件的ID,以便把它的Value值传进要调用的方法中

4、在前台HTML中用JavaScript调用后台的方法

//计算发行天数 function CountIssueDays()

{

var returnIssueDays=BD0047.CountIssueDays(strIssueDate.value,strMaturityDate.value); strIssueDays.value=returnIssueDays.value;

}

5、再用下面语句触发事件执行Ajax去调用后台的方法

■先获得触发控件的ID

var strIssueDays = document.getElementById("txtIssueDays_txtIssueDays_EditBox"); //发行天数

var strMaturityDate = document.getElementById("txtMaturityDate_txtMaturityDate_EditBox"); //到期日

■触发计算发行天数事件

strIssueDate.attachEvent('onblur',function(){CountIssueDays();}); 

strMaturityDate.attachEvent('onblur',function(){CountIssueDays();});

■注意事项:

1、要在程序load的时候注册类到Ajax

2、要把Ajax引进程序中,再用Using Ajax把它引用进程序中

3、要在网站总目录下有一个Web.config配置文件

用文件编辑器打开它,

在里面的<system.web>下加入以下代码

   <httpHandlers>
      <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
    </httpHandlers>

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页