I have a Function that populates a list box(DiveSiteList) when the page is loaded, and that is working just fine.
namespace DiveApp_WebApplication
{
public partial class HomePage : System.Web.UI.Page
{
private static DiveManager.DiveManager Manager;
protected void Page_Load(object sender, EventArgs e)
{
Manager = new DiveManager.DiveManager();
BindDiveList();
}
private void BindDiveList()
{
foreach (DiveSite DS in Manager.MasterDiveSiteList)
{
ListItem Item = new ListItem();
Item.Text = DS.DiveSiteName;
Item.Attributes.Add("Name", DS.DiveSiteName);
Item.Attributes.Add("Latitude", DS.Latitude.ToString().Replace(",", "."));
Item.Attributes.Add("Longitude", DS.Longitude.ToString().Replace(",","."));
Item.Attributes.Add("ID", DS.DiveSiteID.ToString());
Item.Attributes.Add("Vis", DS.AvarageVisibility.ToString());
Item.Attributes.Add("Depth", DS.MaximumDepth.ToString());
DiveSiteList.Items.Add(Item);
}
}
But now I need nuke and repopulate that list from JavaScript, and I'm not sure how. I tried this, but it says that "an object reference is required for the nonstatic field method or property" on the DiveSiteList(the list box in the web page):
[System.Web.Services.WebMethod()]
private static int BindDiveListWeb()
{
DiveSiteList.Items.Clear();
foreach (DiveSite DS in Manager.MasterDiveSiteList)
{
ListItem Item = new ListItem();
Item.Text = DS.DiveSiteName;
Item.Attributes.Add("Name", DS.DiveSiteName);
Item.Attributes.Add("Latitude", DS.Latitude.ToString().Replace(",", "."));
Item.Attributes.Add("Longitude", DS.Longitude.ToString().Replace(",", "."));
Item.Attributes.Add("ID", DS.DiveSiteID.ToString());
Item.Attributes.Add("Vis", DS.AvarageVisibility.ToString());
Item.Attributes.Add("Depth", DS.MaximumDepth.ToString());
DiveSiteList.Items.Add(Item);
}
return 1;
}
I tried a few different things but I'm a bit lost, can anyone help?
Edit: MasterDiveSiteList
public List<DiveSite> MasterDiveSiteList;
DiveDBClass = new DBAccessClass();
Initialize();
private void Initialize()
{
MasterDiveSiteList = DiveDBClass.GetAllDiveSites();
}
When you populate the list the first time, the instance exists because it executes within the context of the page.
When you call the method via JavaScript however, you are using a static instance which does not have the context you had before when loading the page.
The correct way to do this is to have the JavaScript method receive the list of items. You can then populate them on the client side.
Check this out: