• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

CodeSmith系列(三)——使用CodeSmith生成ASP.NET页面

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

  仍然使用之前的XML文件,然后设置生成参数如下:

生成调整后的页面如下:

生成的代码如下:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ConfirmationForPayment.ascx.cs"
    Inherits="NBShop.UserControls.Form.ConfirmationForPayment" EnableViewState="true" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<ext:ResourceManager ID="ResourceManager1" runat="server" />
<script type="text/javascript">
    var valCss = '';
    function showMsg(title, content, cs) {
        if (valCss != cs) {
            valCss = cs;
            Ext.net.Notification.show({
                hideFx: {
                    fxName: 'switchOff',
                    args: [{}]
                },
                showFx: {
                    args: [
                              'C3DAF9',
                              1,
                              {
                                  duration: 2.0
                              }
                          ],
                    fxName: 'frame'
                },
                iconCls: cs,
                closeVisible: true,
                html: content,
                title: title + '   ' + new Date().format('g:i:s A')
            });
        }
    }
</script>
<center>
    <div style="width: 830px; text-align: left;">
        <ext:FormPanel ID="FormPanel1" Collapsible="true" Header="false" Icon="PageAdd" runat="server"
            MonitorVal
            Width="830px" Layout="Form">
			<Items>
				<ext:FormPanel ID="fpGroup0" Icon="PhoneAdd" Border="true" Collapsible="true" runat="server" Title="表单信息" AutoHeight="true" LabelWidth="120">
	<Items>
	<ext:TableLayout runat="server" ColumnWidth="0.5" Columns="2"><Cells><ext:Cell><ext:TextField ID="txtAreaName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtBranchCompany" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtProvince" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtCitys" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtShopName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtName" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtOracleNO" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtMarginNumber" runat="server" /></ext:Cell>
	<ext:Cell><ext:DateField ID="txtPayTime" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtPayer" runat="server" /></ext:Cell>
	<ext:Cell ColSpan="2"><ext:FormPanel Border="false" IsFormField="true" ID="tblPaymentAmount" runat="server" ><Items><ext:DisplayField runat="server" Text="---动态生成--" /></Items></ext:FormPanel></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlCollectingCompany" runat="server" /></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlDueBank" runat="server" /></ext:Cell>
	<ext:Cell><ext:ComboBox Editable="false" ID="ddlCollectingBankAccount" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtBranchContacts" runat="server" /></ext:Cell>
	<ext:Cell><ext:TextField ID="txtContactPhoneNumber" runat="server" /></ext:Cell>
	<ext:Cell ColSpan="2"><ext:FormPanel Border="false" IsFormField="true" ID="tblFinancialConfirm" runat="server" ><Items><ext:DisplayField runat="server" Text="---动态生成--" /></Items></ext:FormPanel></ext:Cell>
	</Cells>   </ext:TableLayout></Items>
	</ext:FormPanel>
	
                    <ext:Panel ID="pnlExamineList" runat="server" Collapsible="true" Header="true" Icon="UserFemale" Border="true"
                    Title="审批历史" Height="200">
                    <AutoLoad Url="/FormServerTemplates/ExamineList.aspx" NoCache="true" Mode="IFrame"
                        ShowMask="true" />
                    <Listeners>
                        <Expand Handler="this.reload();" />
                        <Collapse Handler="this.clearContent();" />
                    </Listeners>
                </ext:Panel>
			</Items>
			<Buttons>
                <ext:Button ID="btnSave" runat="server" Text="保存" CausesValidation="true" Icon="Disk">
                    <DirectEvents>
                        <Click OnEvent="btnSave_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
                <ext:Button ID="btnSumbit1" runat="server" Text="提交" CausesValidation="true" Icon="PageAdd">
                    <DirectEvents>
                        <Click OnEvent="btnSubmit_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
            </Buttons>
            <BottomBar>
                <ext:StatusBar ID="StatusBar1" runat="server" />
            </BottomBar>
            <TopBar>
                <ext:Toolbar ID="Toolbar1" runat="server">
                    <Items>
                        <ext:ToolbarFill ID="ToolbarFill1" runat="server"/>
                        <ext:Button ID="tbSave" runat="server" Icon="Disk" CausesValidation="true" Text="保存">
                            <DirectEvents>
                                <Click OnEvent="btnSave_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理数据..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                        <ext:Button ID="btnSumbit2" runat="server" Icon="PageAdd" CausesValidation="true" 
                            Text="提交">
                            <DirectEvents>
                                <Click OnEvent="btnSubmit_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                    </Items>
                </ext:Toolbar>
            </TopBar>
            <Listeners>
                <ClientValidation Handler="#{btnSave}.setDisabled(!valid);#{tbSave}.setDisabled(!valid);#{btnSumbit1}.setDisabled(!valid);#{btnSumbit2}.setDisabled(!valid);var valCs=valid ? 'valaccept' : 'valexclamation';var msg=valid ? '<span style=\'color:green;\'>验证通过,可以提交数据</span>' : '<span style=\'color:red;\'>输入有误,请检查标红的输入项。</span>';this.getBottomToolbar().setStatus({text :msg, iconCls: valCs});showMsg('温馨提示',msg,valCs);" />
            </Listeners>
        </ext:FormPanel>
	</div>
</center>
<script type="text/javascript">
    Ext.onReady(function () {
        $(function(){
            setTimeout("setLabelClass()",300);            
        });
        //当前窗体最大化
        top.Ext.getCmp('frmStatesRequestList').maximize();
    });     
    function setLabelClass() {
        //表单控件设置Label样式
        $("label.x-form-item-label").addClass("labelStyle");
        //设置表格宽度
        $("table.x-table-layout").attr("width", "100%");
    } 
</script>

模板如下:

<%-- 
Name: 根据XML生成用户控件表单
Author: LWQ
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Html" Debug="True"
CompilerVersion="v3.5" Description="根据XML生成Ext.NET用户控件" ResponseEncoding="UTF-8"%>

<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Property Name="ClassName" Type="System.String" Default="" Optional="True" Category="Optional" Description="用户控件名称。" %>
<%--加载使用访问数据库的组件SchemaExplorer,并声明其使用的命名空间。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context"  Description="对应的数据主表" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%--加载Linq to xml组件,并声明其使用的命名空间。--%>
<%@ Import Namespace="System.Xml.Linq" %>
<%@ Assembly Name="System.Xml.Linq" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Windows.Forms.Design"%>
<%@ Assembly Name="System.Design" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%%@ Control Language="C#" AutoEventWireup="true" CodeBehind="<%=ClassName%>.ascx.cs"
    Inherits="NBShop.UserControls.Form.<%=ClassName%>" EnableViewState="true" %>
<%%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<ext:ResourceManager ID="ResourceManager1" runat="server" />
<script type="text/javascript">
    var valCss = '';
    function showMsg(title, content, cs) {
        if (valCss != cs) {
            valCss = cs;
            Ext.net.Notification.show({
                hideFx: {
                    fxName: 'switchOff',
                    args: [{}]
                },
                showFx: {
                    args: [
                              'C3DAF9',
                              1,
                              {
                                  duration: 2.0
                              }
                          ],
                    fxName: 'frame'
                },
                iconCls: cs,
                closeVisible: true,
                html: content,
                title: title + '   ' + new Date().format('g:i:s A')
            });
        }
    }
</script>
<center>
    <div style="width: 830px; text-align: left;">
        <ext:FormPanel ID="FormPanel1" Collapsible="true" Header="false" Icon="PageAdd" runat="server"
            MonitorVal
            Width="830px" Layout="Form">
			<Items>
				<%=GetFormItem()%>
                    <ext:Panel ID="pnlExamineList" runat="server" Collapsible="true" Header="true" Icon="UserFemale" Border="true"
                    Title="审批历史" Height="200">
                    <AutoLoad Url="/FormServerTemplates/ExamineList.aspx" NoCache="true" Mode="IFrame"
                        ShowMask="true" />
                    <Listeners>
                        <Expand Handler="this.reload();" />
                        <Collapse Handler="this.clearContent();" />
                    </Listeners>
                </ext:Panel>
			</Items>
			<Buttons>
                <ext:Button ID="btnSave" runat="server" Text="保存" CausesValidation="true" Icon="Disk">
                    <DirectEvents>
                        <Click OnEvent="btnSave_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
                <ext:Button ID="btnSumbit1" runat="server" Text="提交" CausesValidation="true" Icon="PageAdd">
                    <DirectEvents>
                        <Click OnEvent="btnSubmit_Click" Single="true">
                            <EventMask ShowMask="true" Msg="正在处理..." />
                        </Click>
                    </DirectEvents>
                </ext:Button>
            </Buttons>
            <BottomBar>
                <ext:StatusBar ID="StatusBar1" runat="server" />
            </BottomBar>
            <TopBar>
                <ext:Toolbar ID="Toolbar1" runat="server">
                    <Items>
                        <ext:ToolbarFill ID="ToolbarFill1" runat="server"/>
                        <ext:Button ID="tbSave" runat="server" Icon="Disk" CausesValidation="true" Text="保存">
                            <DirectEvents>
                                <Click OnEvent="btnSave_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理数据..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                        <ext:Button ID="btnSumbit2" runat="server" Icon="PageAdd" CausesValidation="true" 
                            Text="提交">
                            <DirectEvents>
                                <Click OnEvent="btnSubmit_Click" Single="true">
                                    <EventMask ShowMask="true" Msg="正在处理..." />
                                </Click>
                            </DirectEvents>
                        </ext:Button>
                    </Items>
                </ext:Toolbar>
            </TopBar>
            <Listeners>
                <ClientValidation Handler="#{btnSave}.setDisabled(!valid);#{tbSave}.setDisabled(!valid);#{btnSumbit1}.setDisabled(!valid);#{btnSumbit2}.setDisabled(!valid);var valCs=valid ? 'valaccept' : 'valexclamation';var msg=valid ? '<span style=\'color:green;\'>验证通过,可以提交数据</span>' : '<span style=\'color:red;\'>输入有误,请检查标红的输入项。</span>';this.getBottomToolbar().setStatus({text :msg, iconCls: valCs});showMsg('温馨提示',msg,valCs);" />
            </Listeners>
        </ext:FormPanel>
	</div>
</center>
<script type="text/javascript">
    Ext.onReady(function () {
        $(function(){
            setTimeout("setLabelClass()",300);            
        });
        //当前窗体最大化
        top.Ext.getCmp('frmStatesRequestList').maximize();
    });     
    function setLabelClass() {
        //表单控件设置Label样式
        $("label.x-form-item-label").addClass("labelStyle");
        //设置表格宽度
        $("table.x-table-layout").attr("width", "100%");
    } 
</script>
<script runat="template">
     ///配置文件路径
     private string _userFileName = string.Empty;
     [Editor(typeof(FileNameEditor), typeof(System.Drawing.Design.UITypeEditor)),Category("Custom"), Description("请选择配置XML文件。")]
     public string UserFileName
     {
          get {return _userFileName;}
          set {_userFileName= value;}
     }
     //返回生成的项的HTML
      public string GetFormItem()
     {
          Debugger.Break();
          if (File.Exists(_userFileName))
          {
               StringBuilder _sbText = new StringBuilder();
               XElement elements = XElement.Load(_userFileName);
               var _group = elements.Descendants("Group");
               if (_group == null || _group.Count() == 0)
               {
                   var _fields = elements.Descendants("Field");
                   CreateFields(_sbText, _fields);
               }
               else
               {
                    int _groupIndex=0;
                   foreach (var item in _group)
                   {
                       var _GroupID = item.Attribute("GroupID") == null ? "fpGroup"+_groupIndex : item.Attribute("GroupID").Value;
                       var _title = item.Attribute("Title") == null ? string.Empty : item.Attribute("Title").Value;
                       var _Columns = item.Attribute("Columns") == null ? string.Empty : item.Attribute("Columns").Value;
                       _sbText.Append("<ext:FormPanel ID=\"").Append(_GroupID).Append("\" Icon=\"PhoneAdd\" Border=\"true\" Collapsible=\"true\" runat=\"server\" Title=\"").Append(_title).Append("\" AutoHeight=\"true\" LabelWidth=\"120\">\r\n\t<Items>\r\n\t");
                       _sbText.Append("<ext:TableLayout runat=\"server\" ColumnWidth=\"");
                       switch (_Columns)
                       {
                           case "2":
                               _sbText.Append("0.5");
                               break;
                           case "3":
                               _sbText.Append("0.33");
                               break;
                           case "4":
                               _sbText.Append("0.25");
                               break;
                           case "1":
                               _sbText.Append("1");
                               break;
                           default:
                               break;
                       }
                       _sbText.Append("\" Columns=\"").Append(_Columns).Append("\"><Cells>");
                       var _fields = item.Descendants("Field");
                       CreateFields(_sbText, _fields);
                       _sbText.Append("</Cells>   </ext:TableLayout>");
                       _sbText.Append("</Items>\r\n\t</ext:FormPanel>\r\n\t");
                      _groupIndex++;
                   }
               }
               return _sbText.ToString();
            }
          return string.Empty;
     }
      private void CreateFields(StringBuilder _sbText, IEnumerable<XElement> _fields)
    {
        foreach (var item in _fields)
        {
          
            //文本控件ID
            string _textControlID = item.Attributes("TextControlID").First().Value;
            string _attr = _textControlID.Substring(0, 3);
            string _fieldName=_textControlID.Substring(3);

            if (_attr == "tbl")
                _sbText.Append("<ext:Cell ColSpan=\"2\">");
            else
                _sbText.Append("<ext:Cell>");

            //判断是否为数字
            if (item.Attributes("MaximumValue").FirstOrDefault() != null || item.Attributes("MinimumValue").FirstOrDefault() != null)
            {
                _sbText.Append("<ext:NumberField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
            }
            else
            {
                switch (_attr)
                {
                    case "txt":
                        if ( _textControlID.ToLower().Contains("date") 
                              || _textControlID.ToLower().Contains("time") 
                              || _textControlID.ToLower().Contains("DeadLine")
                              || _textControlID.ToLower().Contains("birthday")
                              )
                            _sbText.Append("<ext:DateField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        else
                            _sbText.Append("<ext:TextField ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    case "ddl":
                        _sbText.Append("<ext:ComboBox Editable=\"false\" ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    case "cbl":
                        _sbText.Append("<ext:CheckboxGroup ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:Checkbox runat=\"server\" BoxLabel=\"测试\" /> </Items></ext:CheckboxGroup>");
                        break;
                    case "rbl":
                        _sbText.Append("<ext:RadioGroup ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:Radio runat=\"server\" BoxLabel=\"测试\" /> </Items></ext:RadioGroup>");
                        break;
                    case "tbl":
                        _sbText.Append("<ext:FormPanel Border=\"false\" IsFormField=\"true\" ID=\"").Append(_textControlID).Append("\" runat=\"server\" ><Items><ext:DisplayField runat=\"server\" Text=\"---动态生成--\" /></Items></ext:FormPanel>");
                        break;
                    case "chk":
                        _sbText.Append("<ext:Checkbox ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                     case "rdo":
                        _sbText.Append("<ext:Radio ID=\"").Append(_textControlID).Append("\" runat=\"server\" />");
                        break;
                    default:
                        Response.WriteLine("警告:代码生成错误。未知的控件前缀:"+_attr);
                        return;
                }
            }
            _sbText.Append("</ext:Cell>\r\n\t");
        }
    }
</script>

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
在asp.net中动态生成web控件发布时间:2022-07-10
下一篇:
ASP.NET系统用户权限设计与实现发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap