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

简介: 仍然使用之前的XML文件,然后设置生成参数如下: 生成调整后的页面如下: 生成的代码如下: var valCss = ''; function showMsg(title, content, cs) { if (valCss != cs) { valCss = cs; Ext.

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

image

生成调整后的页面如下:

image

生成的代码如下:

<%@ 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"
            MonitorValid="true" Padding="5" ButtonAlign="Right"
            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"
            MonitorValid="true" Padding="5" ButtonAlign="Right"
            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>
目录
相关文章
|
JavaScript 前端开发
vue 部署项目,访问页面空白,找不到js或css文件 (net::ERR_ABORTED 404 (Not Found))
vue 部署项目,访问页面空白,找不到js或css文件 (net::ERR_ABORTED 404 (Not Found))
2802 0
vue 部署项目,访问页面空白,找不到js或css文件 (net::ERR_ABORTED 404 (Not Found))
|
4月前
|
开发框架 JavaScript 前端开发
揭秘:如何让你的asp.net页面变身交互魔术师——先施展JavaScript咒语,再引发服务器端魔法!
【8月更文挑战第16天】在ASP.NET开发中,处理客户端与服务器交互时,常需先执行客户端验证再提交数据。传统上使用ASP.NET Button控件直接触发服务器事件,但难以插入客户端逻辑。本文对比此法与改进方案:利用HTML按钮及JavaScript手动控制表单提交。后者通过`onclick`事件调用JavaScript函数`SubmitForm()`来检查输入并决定是否提交,增强了灵活性和用户体验,同时确保了服务器端逻辑的执行。
50 5
|
7月前
|
开发框架 .NET 中间件
七天.NET 8操作SQLite入门到实战 - (2)第七天Blazor班级管理页面编写和接口对接
七天.NET 8操作SQLite入门到实战 - (2)第七天Blazor班级管理页面编写和接口对接
153 7
|
4月前
|
开发框架 前端开发 .NET
七天.NET 8操作SQLite入门到实战 - (3)第七天Blazor学生管理页面编写和接口对接
七天.NET 8操作SQLite入门到实战 - (3)第七天Blazor学生管理页面编写和接口对接
|
JavaScript
Vue 打包后打开为空白页面 并且控制台报错‘Failed to load resource: net::ERR_FILE_NOT_FOUND’
Vue 打包后打开为空白页面 并且控制台报错‘Failed to load resource: net::ERR_FILE_NOT_FOUND’
Vue 打包后打开为空白页面 并且控制台报错‘Failed to load resource: net::ERR_FILE_NOT_FOUND’
|
开发框架 数据可视化 前端开发
ASP.NET Core MVC+Quartz实现定时任务可视化管理页面
ASP.NET Core MVC+Quartz实现定时任务可视化管理页面
593 0
|
开发框架 JavaScript .NET
Asp.net C#页面传参的几种方式
Asp.net C#页面传参的几种方式
145 0
mvc.net分页查询案例——前台页面(Index.aspx)
mvc.net分页查询案例——前台页面(Index.aspx)
|
开发框架 JSON 前端开发
【C#】.net core2.1,自定义全局类对API接口和视图页面产生的异常统一处理
在开发一个网站项目时,异常处理和过滤功能是最基础的模块 本篇文章就来讲讲,如何自定义全局异常类来统一处理
240 0

相关实验场景

更多