如何从aspx代码后面访问我的公共方法到公共类?

时间:2012-04-25 14:44:10

标签: c# asp.net

我的aspx代码后面有一个名为PhotoDatabinding的公共方法,它的作用是将数据库绑定到List视图控件。

public void PhotoDatabinding()
{


lnqPhotoDataContext dbCon = new lnqPhotoDataContext();
var res = from p in dbCon.Photos orderby p.PhotoID descending select new {          p.PhotoID, p.FileName };

    lvSubAlbumDB.DataSource = res;
    lvSubAlbumDB.DataBind();

 }

现在,在我的名为Process的公共类中,我有一个名为UpdateSave的方法。我的问题是我如何访问PhotoBinding方法,使它看起来像这样

public class Process
{
public UpdateSave()
{
    ....some code
    PhotoDatabinding();

}

}

感谢并感谢您的所有帮助和建议。

1 个答案:

答案 0 :(得分:1)

清除流程:

您需要创建一个仅用于从数据库获取数据或更新数据的类

public class PhotoAccess
{

  public class PhotoInfo
  {
    public int PhotoID {get; set;}
    public string FileName {get; set;}
  }

  public IEnumerable<PhotoInfo> GetPhotos()
  {
   using ( var dbCon = new lnqPhotoDataContext())
   {
      var res = from p in dbCon.Photos 
            orderby p.PhotoID descending 
            select new PhotoInfo 
                       {
                          p.PhotoID, 
                          p.FileName 
                       };
      return res.AsEnumerable();
    }
  }
  public bool UpdateSave(...)
  {
      ... code to do update or save, use here only classes for working with the DB
  }
}

然后在页面背后的代码中

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
       var dataAccess = new PhotoAccess();
       var items = dataAccess.GetPhotos();

       lvSubAlbumDB.DataSource = items;
       lvSubAlbumDB.DataBind();
   }
}
protected void btSave_OnClick(object sender, EventArgs e)
{
    var dataAccess = new PhotoAccess();
    dataAccess.UpdateSave(...pass here the parameters or an object which is going to be inserted);

    var items = dataAccess.GetPhotos();

    lvSubAlbumDB.DataSource = items;
    lvSubAlbumDB.DataBind();
}

您也可以将绑定代码重构为Page类

的另一种方法
private void BindAlbum()
{
   var dataAccess = new PhotoAccess();
   var items = dataAccess.GetPhotos();    

   lvSubAlbumDB.DataSource = items;
   lvSubAlbumDB.DataBind();
}

页面加载将是:

 protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
       {
           BindAlbum();
       }
    }

和更新处理程序

 protected void btSave_OnClick(object sender, EventArgs e)
    {
        var dataAccess = new PhotoAccess();
        dataAccess.UpdateSave(...pass here the parameters or an object which is going to be inserted);

        BindAlbum();
    }