自己寫一個DropDownList控件

預備知識:

1.關於object.Equals(objA,objB)方法

namespace ObjectEqua方法探究
{
    class Program
    {
        static void Main(string[] args)
        {

            int i = 1;
            int j = 1;
            object objA = i;
            object objB = j;
            Console.WriteLine(i==j);//True                          //int ;類重載了 == 運算符

            //因爲obj1和obj2是兩個箱子,所以是false
            Console.WriteLine(objA==objB);//False                   //==號是可以重載的(運算符重載),默認實現是比較是否是同一個對象


            Console.WriteLine(object.Equals(objA, objB));//True     確定指定的對象實例是否被視爲相等。-----拆箱之後比較兩個實例是否相等

            Console.WriteLine(objA.Equals(objB));//True             確定指定的 System.Object 是否等於當前的 System.Object。
            Console.ReadKey();


            string  // 類中F12觀察, == 號運算符重載了 確定兩個指定的字符串是否具有相同的值。

            //對於兩個object類型的變量比較,或者一個object和一個int/string等變量比較,最好使用Object.Equals(obj1,obj2)
        }
    }
}

2.關於反射

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _反射覆習
{
    class Program
    {
        static void Main(string[] args)
        {

            Type p = typeof(Person);//拿到了類名字
            Console.WriteLine(p);
            MemberInfo[] methes = p.GetMembers();//拿到反射類中的方法
            foreach (MemberInfo item in methes)//遍歷出所有的方法名字
            {
                Console.WriteLine(item.Name);
            }
            Console.WriteLine("============================================");

            //可以直接獲取person這個類中的屬性
            PropertyInfo[] ps = p.GetProperties();

            //拿到數組就遍歷
            for (int i = 0; i < ps.Length; i++)
            {

                Console.WriteLine(ps[i].Name);//獲取類中所有屬性的名字

            }


            Console.ReadKey();
        }
    }

    class Person
    {
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public void Voice()
        {
            Console.WriteLine("我是人");
        }


        public void Show()
        {
            Console.WriteLine("衣服");
        }
    }
}

瞭解更多反射….

案例:

案例概要

1,編寫一個靜態方法,
2,然後在cshtml頂部using “類” 所在的命名空間namespace(比如: @using Web ),(一般是你的項目名字)
3,然後在cshtml中就可以@MyHelper.Test() 輸出。

案例要求

生成一個 DropdownList 控件
public static RawString DropDownList(IEnumerable items,string textField,string valueField,object selectedValue,string name,string id),

步驟

1.封裝一個RPcshtmlHelper.cs的類,這樣可以避免在cshtml模板頁中寫大量的代碼,是cshtml模板頁看着更加的簡潔,清晰。

using RazorEngine;
using RazorEngine.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;

namespace Web2
{
    public class RPcshtmlHelper
    {
        //弄清關係,不要懷疑工具的錯誤,檢查自己操作的問題

        //1.封裝一個方法,省去了每次都重複自己添加cacheName的麻煩
        public static string ParseRazor(HttpContext context, string csHtmlVirtualPath, object model)
        {
            //2.拿到虛擬路徑
            string fullPath = context.Server.MapPath(csHtmlVirtualPath);
            //3.讀取模板
            string cshtml = File.ReadAllText(fullPath);
            //4.給模板文件取一個別名字
            string cacheName = fullPath + File.GetLastWriteTime(fullPath);
            //5.用model替換變量
            string html = Razor.Parse(cshtml, model, cacheName);
            //6.返回模板文件內容
            return html;
        }

        //1.定義一個簡單的《靜態》方法,作爲測試,這裏的方法是在cshtml模板文件中調用的
        public static HtmlEncodedString Test1()
        {
            return new HtmlEncodedString("<input type='text' />");

        }
        // 同樣定義第二個《靜態》方法
        public static RawString Test2()
        {
            return new RawString("<input type='text' />");

        }

        public static RawString CheckBox(string name, string id, bool isChecked)//標籤有名字,id,和是否選中
        {
            //1.new一個StringBuilder
            StringBuilder ss = new StringBuilder();
            //2.拼接一個CheckBox方法
            ss.Append("<input type='checkbox' id=' ").Append(id).Append("'").Append("name='").Append(name).Append("'");
            if (isChecked)//如果是選中的
            {
                ss.Append("checked");
            }
            ss.Append("/>");
            return new RawString(ss.ToString());//返回生成的標籤
        }

        public static string Test3()
        {

            return "<input type='text' id='name' />";
        }

        /// <summary>
        /// 使得傳遞進去的字符串都是按照原樣輸出到瀏覽器中執行
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static RawString Raw(string str)
        {
            return new RawString(str);
        }

        //無論是 數組。List都實現了IEnumerable接口,而且是非泛型的
        //比如

        //Person[] persons=.....
        //DropDownList(person,"Id","Name",3,new{id="mangerId",name="m1",style="color:red"});
        //<select id="managerId" name="m1" style="color:red">
        //    <option value="1" >rupeng</option>
        //    <option value="2" selected>xcl</option>
        //    <option vlaue="3' >beijing</option>
        //</select>
        public static RawString DropDownList(IEnumerable items, string valuePropName, string textPropName, object selectedValue, object extenedProperties)//1-1.這裏extenedProperties是指的就是匿名類名字,它也是屬於objec類型的
        {

            StringBuilder sb = new StringBuilder();

            //1.1 拼接出來 “select”標籤----------------這裏一堆代碼主要是 拼接 關於select 的屬性集合
            sb.Append("<select");
            //用反射類Type調用程序集中的方法
            Type extendPropertiesType = extenedProperties.GetType();//1-2.既然是類就可以反射拿到類的名字,實例化創建對象;
            PropertyInfo[] extPropInfos = extendPropertiesType.GetProperties();//1-3.反射獲取類中的屬性;
            foreach (var extPropInfo in extPropInfos)//1-4.所以這裏就可以遍歷
            {
                string extProName = extPropInfo.Name;//1-5.取得屬性的名字
                object extPropValue = extPropInfo.GetValue(extenedProperties);
                sb.Append(" ").Append(extProName).Append("='").Append(extPropValue).Append("'");

            }
            sb.Append(">");

            //2.2 拼接出來 “option” 標籤----------------這裏一堆代碼主要是 拼接 關於option 的屬性集合
            foreach (Object item in items)
            {
                Type itemType = item.GetType();//獲得對象類型的名字

                PropertyInfo valuePropInfo = itemType.GetProperty(valuePropName);//拿到valuePropName("Id")的屬性
                object itemValueValue = valuePropInfo.GetValue(item);//獲得就是item對象的“Id”的值

                PropertyInfo textPropInfo = itemType.GetProperty(textPropName);//拿到“Name”的屬性
                object itemTextValue = textPropInfo.GetValue(item);//拿到item的“Name”屬性的值

                //等於selectedValue的項增加一個“selecte”屬性,它被選中
                sb.Append("<option value='").Append(itemValueValue).Append("'");
                if (Object.Equals(itemValueValue ,selectedValue))
                {
                    sb.Append("selected");
                }
                sb.Append(">").Append(itemTextValue).Append("</option>");
            }

            sb.Append("</select>");
            return new RawString(sb.ToString());
        }
    }
}

2.添加一個html頁,修改爲cshtml模板頁,在模板頁中就可以調用RPcshtmlHelper中的方法了

<!--1.收先在模板文集中讀取RPcshtmlHelper的命名空間-->
@using Web2
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>

        <!--2.調用方法測試的方法Test1-->
     html標籤轉義過的   @RPcshtmlHelper.Test1()<br />
    html標籤沒有轉義過的   @RPcshtmlHelper.Test2()
    <!--3.添加一個一般處理處理程序,調用該模板文件-->


    <!--11.調用類中的方法-->
    @RPcshtmlHelper.CheckBox("gender","sex",true)

    <!--測試字符串的返回-->
    @RPcshtmlHelper.Test3()

    <!--測試匿名類中包含html標籤的字符串的返回-->
    @Model.Zifu
    @RPcshtmlHelper.Raw(Model.Zifu)
    @{
        string str = RPcshtmlHelper.Test3();
        }
    @RPcshtmlHelper.Raw(str)

    <br />
    <!--調用類中的DropDownList方法,生成下拉列表-->
    @RPcshtmlHelper.DropDownList(Model.Persons, "Id", "Name", Model.PersonId, new{id="m1",name="m2",style="color:red" })
    <br /><br />
    <!--調用類中的DropDownList方法,生成下拉列表-->
    @RPcshtmlHelper.DropDownList(Model.Persons, "Id", "Age", Model.PersonId, new { id="bj",name="province",
    style="color:red",onchange="alert(\"hello\")",haha="ss"})

</body>
</html>

3.添加一個Persons類,模仿從數據庫中調過來的字段

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

namespace Web2
{
    public class Persons
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

4.添加一個Razor2.ashx一般處理程序,用來讀取模板文件cshtml

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

namespace Web2
{
    /// <summary>
    /// Razor2 的摘要說明
    /// </summary>
    public class Razor2 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";//1.修改爲html

            //2.調用封裝的方法ParseRazor
          // string html= RPcshtmlHelper.ParseRazor(context, "~/Razor2.cshtml",null);

            //使用一個泛型集合
            List<Persons> list = new List<Persons>();
            list.Add(new Persons { Id=1,Name="rupeng",Age=12});
            list.Add(new Persons { Id=2,Name="xcl",Age=20});
            list.Add(new Persons{Id=3,Name="雷軍",Age=30});
            list.Add(new Persons { Id=4,Name="騰訊",Age=20});


            //測試匿名類中傳遞參數
           string html = RPcshtmlHelper.ParseRazor(context, "~/Razor2.cshtml", new { Name="xcl",Zifu="C#中的泛型 表示:List<String>",Persons=list,PersonId=2});//兩個新的屬性

            //3.將轉化過的模板內容輸入到瀏覽器
            context.Response.Write(html);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

5.打開瀏覽器,訪問Razor2.ashx頁面,訪問結果如下

這裏寫圖片描述

做後分析

這裏寫圖片描述

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章