On Static WebMethod I'm unable to get ListBoxcontrol, so I have stored that control in session on Page_Load event as:
HttpContext.Current.Session["LB_AvailFields"] = lbavailablefields;
After calling WebMethod I'm getting values from Database and trying to fill ListBox but ListBox not showing any values. Following is hardcoded testing code which works fine on Page_Load but not in WebMethod please suggest where I'm going wrong?
List<MyListItem> LB = new List<MyListItem>();
MyListItem lbitem;
for(int i= 0;i<5;i++)
{
lbitem = new MyListItem();
lbitem.PMKey = "Key" + i;
lbitem.PMSystemName = "SystemName: " + i;
LB.Add(lbitem);
}
ListBox lbox = (ListBox)HttpContext.Current.Session["LB_AvailFields"];
lbox.DataSource = LB;
lbox.DataTextField = "PMSystemName";
lbox.DataValueField = "PMKey";
lbox.DataBind();
The WebMethod concept is to give you a quick web service like experience. The web page doesn't exist on the server, as it does when Page_Load works. The intended use is to call web methods from client script, return data to client side and consume there (javascript)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyReturnResultObject[] GetListBoxData()
{
List<MyReturnResultObject> result = new List<MyReturnResultObject>();
loop to fill your return result
{
var oneResult = new MyReturnResultObject();
...
result.Add(oneResult);
}
return result.toArray();
}
Then on the client side, where you use javascript to call that method, just use the returned json to populate your listbox (using javascript). There are many ways to do this in javascript, showing most rudimentary; if jQuery is available to you you could use it.
var myList = ...; // obtain a reference to your list box
var anOption;
loop through json
anOption = document.createElement("Option");
anOption.text = ...; //from json
anOption.value = ...; //from json
myList.add(anOption);