前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自己写一个DropDownList控件

自己写一个DropDownList控件

作者头像
静心物语313
发布2020-03-24 14:29:22
8390
发布2020-03-24 14:29:22
举报

预备知识:

1.关于object.Equals(objA,objB)方法

代码语言:javascript
复制
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.关于反射

代码语言:javascript
复制
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模板页看着更加的简洁,清晰。
代码语言:javascript
复制
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中的方法了
代码语言:javascript
复制
<!--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",οnchange="alert(\"hello\")",haha="ss"})

</body>
</html>
3.添加一个Persons类,模仿从数据库中调过来的字段
代码语言:javascript
复制
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
代码语言:javascript
复制
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页面,访问结果如下
这里写图片描述
这里写图片描述

做后分析

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 预备知识:
    • 1.关于object.Equals(objA,objB)方法
      • 2.关于反射
        • 案例:
          • 案例概要
          • 案例要求
          • 步骤
      • 做后分析
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档