咨询电话:186 7916 6165 咨询电话:186 7916 6165 (微信同号)    在线QQ:181796286
NEWS BLOG ·
学无止境
关注开优网络 关注前沿
ASP.NET常用服务器控件方法及属性
ASP.NET 关键词keywords与description的设置

ASP.NET Web 开发之代码生成及增、删、改

发表日期:2015-12-02    文章编辑:南昌开优网络    浏览次数:4246    标签:ASP.NET应用

配置2.75动软生成器
工具 → 选项 → 基本设置 → 顶级命名空间 → Xiaobin.Shop
数据访问基类 → DbHelperSQL
项目名称 → demo_
存储过程前缀 → up_
类命名规则  首字母大写  DAL → 表名+DAL
选择默认代码模板 DAL → BuilderDALELParam  //基于企业库param方式
批量生成代码时去掉数据表的前缀如:shop_


微软企业库配置Web.confing文件  .net3.5采用Enterprise Library 4.1- October 2008  .net4.0采用 Enterprise Library 5.0
File → open → 找到项目中的web.config文件 → 
Database Sottings → LocalSqlServer →   //连接的数据库
Namae → XiaobinShopConnStr →    //连接的名称
Database → System.Data.SqlClient → //数据库的类型
Connection → server=.\sqlexpress;database=xiaobinshop;uid=sa;pwd=123456; → //连接地址
Database Sottings → Default → XiaobinShopConnStr →   //默认连接地名称

项目中的DAL层中需要引用微软企业库安装文件夹中bin文件夹中的
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll

windows身份验证连接数据库
<add name="XiaobinCMSConnStr" connectionString ="Integrated Security=sspi; server=.\sqlexpress;database=cms;connect timeout=30"  providerName="System.Data.SqlClient"/>
动软自动生成代码修改的地方:
//分页  //fields选择的字段  order排序的字段  ordertype排序方式  PageSize页大小  PageIndex页索引  strWhere条件
public DataSet GetList(string fields, string order, string ordertype, int PageSize, int PageIndex, string strWhere)
{
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("proc_SplitPage");
db.AddInParameter(dbCommand, "tblName", DbType.AnsiString, "bbs_log");
db.AddInParameter(dbCommand, "strFields", DbType.AnsiString, fields);
db.AddInParameter(dbCommand, "PageSize", DbType.Int32, PageSize);
db.AddInParameter(dbCommand, "PageIndex", DbType.Int32, PageIndex);
db.AddInParameter(dbCommand, "strOrder", DbType.String, order);
db.AddInParameter(dbCommand, "strOrderType", DbType.String, ordertype);
db.AddInParameter(dbCommand, "strWhere", DbType.AnsiString, strWhere);
return db.ExecuteDataSet(dbCommand);
}


///Model分页
public List<Xiaobin.BBS.Model.Log> GetListArray(string fields, string order, string ordertype, int PageSize, int PageIndex, string strWhere)
{
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("proc_SplitPage");
            db.AddInParameter(dbCommand, "tblName", DbType.AnsiString, "bbs_log");
            db.AddInParameter(dbCommand, "strFields", DbType.AnsiString, fields);
            db.AddInParameter(dbCommand, "PageSize", DbType.Int32, PageSize);
            db.AddInParameter(dbCommand, "PageIndex", DbType.Int32, PageIndex);
            db.AddInParameter(dbCommand, "strOrder", DbType.String, order);
            db.AddInParameter(dbCommand, "strOrderType", DbType.String, ordertype);
            db.AddInParameter(dbCommand, "strWhere", DbType.AnsiString, strWhere);
            List<Xiaobin.BBS.Model.Log> list = new List<Xiaobin.BBS.Model.Log>();          
            using (IDataReader dataReader = db.ExecuteReader(dbCommand)
            {
                while (dataReader.Read())
                {
                    list.Add(ReaderBind(dataReader));
                }
            }
            return list;
}


///计算记录数
  public int CalcCount(string strWhere)
        {
            string sql = "select count(1) from bbs_log";
            if (!string.IsNullOrEmpty(strWhere))
            {
                sql += " where " + strWhere;
            }
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(sql);
            return int.Parse(db.ExecuteScalar(dbCommand).ToString());
        }


//cs.文件执行增、删、改、查 在admin后台中在同一页面中
//页面加载
DAL.LinkDAL dao = new DAL.LinkDAL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                anp.RecordCount = dao.CalcCount(GetCond());
                BindRep();
            }
        }
        //绑定列表
        private void BindRep()
        {
            rep.DataSource = dao.GetList("*", "createdate", "desc", anp.PageSize, anp.CurrentPageIndex, GetCond());
            rep.DataBind();
        }
        //获取条件
        private string GetCond()
        {
            string cond = "";

            if (txtkey.Text.Length != 0)
            {
                string key = txtkey.Text.Trim();
                key = Utility.Tool.GetSafeSQL(key); //过滤非法字符
                string tmp = ddltype.SelectedValue;
                if (tmp == "linkname")
                {
                    cond = " linkname  like '%" + key + "%'";
                }
                else if (tmp == "linkurl")
                {
                    cond = " linkurl like '%" + key + "%'";
                }
            }
            return cond;
        }

       //多条件搜索
      如果是ddl控件时 前台的DropDownList控件 加上AutoPostBack="true" 
      private string GetCond()
        {
           string cond="type='优惠活动'";
          if (txtkey.Text.Length != 0)
            {
                string key = txtkey.Text.Trim();
                key = Utility.Tool.GetSafeSQL(key); //过滤非法字符
                string tmp = ddltype.SelectedValue;    //条件为ddl选中的值
                if (tmp == "linkname")
                {
                    cond += " linkname  like '%" + key + "%'";
                }               
            }
            return cond;
        } 

        //通过传入type值获取条件实现不同的绑定 在Page_load中还是和上面一样
        private string GetCond()
{
    string cond = "1=1";
    string type = Request.QueryString["type"];
    if (!string.IsNullOrEmpty(type))
    {
        cond += " and type=" + type + "";
    }
    if (txtkey.Text.Trim().Length != 0)
    {
        string key = txtkey.Text.Trim();
        key = Xiaobin.Utility.Tool.GetSafeSQL(key);
        cond += " and title like '%" + key + "%' or keyword like '%" + key + "%' ";
    }
    return cond;
}
        
        //分页
        protected void anp_PageChanged(object sender, EventArgs e)
        {
            BindRep();
        }
        //添加
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string linkname = txtnmae.Text.Trim();
            string linkurl = txturl.Text.Trim();

            if (linkname.Length == 0 || linkurl.Length == 0)
            {
                Utility.Tool.Alert("请输入完整再提交", this.Page);
                return;
            }

            if (hfOpreate.Value == "add")
            {
                int res = dao.Add(new Xiaobin.Shop.Model.Link()
                {
                    linkname = linkname,
                    linkurl = linkurl,
                });
                if (res > 0)
                {
                    Utility.Tool.AlertAndGo("添加成功", Request.Url.ToString(), this.Page);
                    return;
                }
                else
                {
                    Utility.Tool.Alert("添加失败,请联系管理员", this.Page);
                    return;
                }
            }
            else if (hfOpreate.Value == "edit")
            {
                string id = hfid.Value;
                int x;
                if (int.TryParse(id, out x))
                {
                    Model.Link model = dao.GetModel(x);
                    if (model != null)
                    {
                        model.linkurl = linkurl;
                        model.linkname = linkname;
                    }
                    dao.Update(model);
                    Utility.Tool.AlertAndGo("修改成功", Request.Url.ToString(), this.Page);
                }
            }
        }
        //删除
        protected void lbtnDel(object sender, EventArgs e)
        {
            string id = (sender as LinkButton).CommandArgument;
            dao.Delete(int.Parse(id));
            Utility.Tool.AlertAndGo("删除成功", Request.Url.ToString(), this.Page);
        }

        //修改
        protected void lbtnMod(object sender, EventArgs e)
        {
            string id = (sender as LinkButton).CommandArgument;
            hfid.Value = id;
            hfOpreate.Value = "edit";
            Model.Link model = dao.GetModel(int.Parse(id));
            if (model != null)
            {
                txtnmae.Text = model.linkname;
                txturl.Text = model.linkurl;
                btnAdd.Text = "修改";
            }
        }
        //搜索
        protected void btnSo_Click(object sender, EventArgs e)
        {
            anp.RecordCount = dao.CalcCount(GetCond());
            BindRep();
        }

如果新建修改页面:如href='link_mod.aspx?id=<%#Eval("id") %>'传入id
string id = Request.QueryString["id"];
int i_id;
if (!string.IsNullOrEmpty(id) && int.TryParse(id, out i_id))
{
Model.Link model = dao.GetModel(i_id);
if (model != null)
{
model.linkurl = linkurl;
model.linkname = linkname;
}
dao.Update(model);
}