不使用ASP.NET服務器端控件(包括form表單不加runat="server")來觸發.cs里的事件(方法),(適用於有代碼潔癖者)。


很多時候,我們使用服務器端控件寫出的代碼,會給我們生成一些很多我們看不懂的代碼(初學者),但是有時候我們並不需要這些代碼(業務需求不同),對於生成的一些代碼感到多余。所以我就開始想,有沒有一種可能:不使用服務器端控件(包括form表單不加runat="server"屬性)來觸發后台寫的某一個方法或事件(ASP.NET的事件實際上是使用事件機制來驅動的)。經過測試是可以的。

原理:使用反射驅動方法。

   步驟:

     1、手寫一個提交表單的js函數(可以使用asp.net的__dopostBack函數來驅動)

   2、使用表單提交到當前這個aspx頁面

   3、使用反射機制來調用指定方法

 

  aspx頁面的代碼:

  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Test.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
//<![CDATA[

        function __doPostBack(eventTarget, eventArgument) {
            var theForm = document.forms['form1'];
            if (!theForm) {
                theForm = document.form1;
            }
            if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
                theForm.__EVENTTARGET.value = eventTarget;
                theForm.__EVENTARGUMENT.value = eventArgument;
                theForm.submit();
            }
        }
//]]>
    </script>
</head>
<body>
    <form action="WebForm1.aspx" method="post" id="form1">
    <input type="hidden" name="__EVENTTARGET" value="" />
    <input type="hidden" name="__EVENTARGUMENT" value="" />
    <input language="javascript" onclick="__doPostBack('Button2','2')" id="Button2" type="button"
        value="Button2" />
    <input language="javascript" onclick="__doPostBack('Button1','1')" id="Button1" type="button"
        value="Button1" />
    <input language="javascript" onclick="__doPostBack('Button3','1')" id="Button3" type="button"
        value="Button3" />
    <a href="#" onclick="__doPostBack('LinkButton1','1')">這是LinkButton(模擬)</a>
    </form>
</body>
</html>
View Code

  

  aspx.cs文件的代碼

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Web.Script.Serialization;

namespace Test
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        public WebForm1() { }

        private string EventTarget
        {
            get
            { return Request.Form["__EVENTTARGET"]; }
        }

        private string EventTargument
        {
            get
            { return Request.Form["__EVENTARGUMENT"]; }
        }


        private new bool IsPostBack
        {
            get
            {
                if (string.IsNullOrEmpty(EventTarget) && string.IsNullOrEmpty(EventTargument))
                {
                    return false;
                }
                return true;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
            else
            {
                Invoke(EventTarget);
            }
        }











        public void ss()
        {
            //取得MyClass的Type對象,下面的代碼使用Type的靜態方法需指明程序集,作用相同  
            //Type t = Type.GetType("Mengliao.CSharp.C13.S02.MyClass, ConsoleApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");  
            Type t = typeof(MyClass);
            //通過Activator實例化MyClass,供實例方法調用  
            object obj = Activator.CreateInstance(t, new object[] { 88 });

            //MethodInfo[] methods = t.GetMethods(); //獲取MyClass的所有方法列表  

            //foreach (MethodInfo nextMethod in methods) //枚舉所有方法  
            //{
            //    Console.WriteLine(nextMethod.ToString()); //顯示方法信息  
            //    if (nextMethod.Name == "m1") //方法m1  
            //    {
            //        nextMethod.Invoke(obj, null); //使用obj對象調用方法m1,無參數  
            //    }
            //    if (nextMethod.Name == "m2") //方法m2  
            //    {
            //        //靜態方法,使用null調用方法m2,建立參數數組,傳入10  
            //        Console.WriteLine("Called static method 2, return {0}", nextMethod.Invoke(null, new object[] { 10 }));
            //    }
            //}

            MethodInfo m3Info = t.GetMethod("Get"); //獲取方法m3  
            m3Info.Invoke(obj, null); //調用方法m3,傳入對應的2個參數  

            //獲取方法m4,使用obj對象調用方法,無參數  
            //t.InvokeMember("m4", BindingFlags.InvokeMethod, null, obj, null);

            ////建立泛型委托runMe,並綁定MyClass的靜態私有方法m5  
            //Delegate runMe = Delegate.CreateDelegate(typeof(Func<double, string>), t, "m5");
            //Console.WriteLine("Call delegate with m5: Sqrt(2) = {0}", ((Func<double, string>)runMe)(2)); //調用該委托  

            //Console.ReadLine();

        }



        public string Invoke(string Method)
        {




            Type t = typeof(MyClass);
            //通過Activator實例化MyClass,供實例方法調用  
            object obj = null;//Activator.CreateInstance(t)
            if (Session["currentObj"] == null)
            {
                obj = Activator.CreateInstance(t);//, new object[] { 88 }
                Session["currentObj"] = obj;
            }
            else
            {
                obj = Session["currentObj"] as object;
            }
            MethodInfo m3Info = t.GetMethod(Method); //獲取方法m3  
            m3Info.Invoke(obj, null); //調用方法m3,傳入對應的2個參數  
            string name = (string)t.InvokeMember(Method, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, obj, null);
            if (!string.IsNullOrEmpty(name))
            {
                Response.Write("<script>alert('" + name + "');</script>");
            }
            return name;
        }


    }

}
View Code

 

  MyClass.cs文件里面就是事件(方法)

  

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

namespace Test
{
    public class MyClass
    {

        public void Button2()
        {
            string str1 = "1";
            string str2 = "2";
        }


        public void Button1()
        {
            string str1 = "1";
            string str2 = "2";
        }

        public string Button3()
        {
            return "hello world";
        }

        public string LinkButton1()
        {
            return "你好";
        }
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM