技术开发 频道

CYQ.Data 轻量数据层之实例开发

  C:留言页面:我们来看一下界面:[这里先清除下数据库的数据,重新注册添加一点数据]

  我先清除以前的旧数据,数据库SQL执行一下语句:

TRUNCATE TABLE [Message]
TRUNCATE TABLE Users

 

  好,重新注册下,留下言,上图:

1
▲

  如上图所示,整个页面分为:

  1:最左上角的欢迎
  2:三个列表[注册用户/我的留言/所有留言],分别使用GridView/DataList/Repeater绑定
  3:右下角的提交留言

  我们一个一个看代码: 

  1:最左上角的欢迎:判断没登陆后就直接转向登陆,如果登陆,直接用Session["ID"]填充数据

protected void LoadMyInfo()
{
        
if (Session["ID"] == null)
        {
            Response.Redirect(
"Login.aspx");
        }
        
else
        {
            MAction action
= new MAction(TableNames.Users);
            
if (action.Fill(Session["ID"]))
            {
                action.SetTo(labUserName);
            }
            
else
            {
                labUserName.Text
= "读取数据失败!";
            }
            action.Close();
        }
}

  2:接下来三个列表的绑定:

protected void LoadUserListInfo()//GridView 绑定用户注册信息
    {
        MAction action
= new MAction(TableNames.Users);
        gvUsers.DataSource
= action.Select();
        gvUsers.DataBind();
        action.Close();
    }
    protected void LoadMyMessageList()
//DataList 绑定我的留言
    {
        
int count;
        MAction action
= new MAction(TableNames.Message);
        dalMyMessage.DataSource
= action.Select(1, 10, string.Format("UserID={0}", Session["ID"]), out count);
        dalMyMessage.DataBind();
        action.Close();
    }
    protected void LoadAllMessageList()
//Repeater 绑定所有用户留言
    {
        MAction action
= new MAction(CustomerSQL.Message);
        rptMessage.DataSource
= action.Select();
        rptMessage.DataBind();
        action.Close();
    }

 

  最后一个绑定所有用户留言时,涉及两个表关联,所以传入的表名是CustomerSQL.Message,这个是怎么来的?

  我App_Code文件夹下我新建一个类:CustomerSQL,来统一管理SQL:

public class CustomerSQL
{
    
public const string Message = "(select m.*,u.UserName from Message m left join Users u on m.UserID=u.ID) v";
}

 

  最后,我们需要在Page_Load方法里加载上面的几个方法:

protected void Page_Load(object sender, EventArgs e)
{
        LoadMyInfo();
        LoadUserListInfo();
        LoadMyMessageList();
        LoadAllMessageList();
}

 

  3:提交留言:提交完后,自我刷新一下界面。

protected void btnSubmit_Click(object sender, EventArgs e)
{
        MAction action
= new MAction(TableNames.Message);
        action.GetFrom(txtBody);
        action.Set(Message.UserID, Session[
"ID"]);
        action.Insert();
        action.Close();
        Response.Redirect(Request.RawUrl);
}

 

  4:还有个退出呢:

protected void btnLogout_Click(object sender, EventArgs e)
{
        Session[
"ID"] = null;
        Response.Redirect(
"Login.aspx");
}

   至此,一个注册+登陆+留言功能的小项目,就轻松写完了,拿上面的代码和你以前写的代码比较下,感觉哪个简洁方便实用呢?

  如果用你目前使用的方法写一个一样的,需要花费的时间和精力又是多少?欢迎拍砖留言!

  OK,本示例应用到此结束了

0
相关文章