Unable to display values in ListBox from static method - asp.net

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);

Related

Kentico CmsRepeater: When to call databind when DataBindByDefault="false"

I want to set DataBindByDefault to false on my repeater because otherwise it makes a call to the db which returns all data from the child nodes of the page which comes to 12MB.
I've hacked it for now and set the Path value to "." (same page only) in the code in front but it's still an extra db call.
So my plan was to set DataBindByDefault to false, assign the data from my custom query to the repeater and then call databind() as follows:
<cms:CMSRepeater ID="repItems" runat="server" Path="."/>
private void InitRepeater()
{
var data = (DataSet)NewsProvider.GetNews(ClassNames, Path, MaxRelativeLevel, OrderBy, WhereStatement, SelectTopN, -1, -1);
if (!DataHelper.DataSourceIsEmpty(data))
{
repItems.DataSource = data;
repItems.ControlContext = ControlContext;
repItems.EnablePaging = true;
repItems.PageSize = PageSize;
repItems.PagerControl.CurrentPage = 1;
repItems.PagerControl.PageSize = PageSize;
repItems.PagerControl.Visible = false;
repItems.HideControlForZeroRows = true;
repItems.TransformationName = Transformation;
repItems.DataBind();
}
}
InitRepeater() is called from SetupControl() which called from OnContentLoaded() and ReloadData() but nothing gets rendered.
If I try calling InitRepeater() in PreRender it renders but it ignores the paging settings.
I'm using Kentico v12.0.65
You should be using the LoadPagesIndividually property of the repeater control. If true, each page is loaded individually in case of paging.

i added a list box in asp.net , i need to get the option set values from ms crm to list box

I am new to ASP.Net I added a list box in asp.net , I need to get the option set values from ms crm to list box
I don't know how to return the value for this can anybody help me
public static string GetMtefrecord()
{
var service = CRMWrapper.GetCRMService();
RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Entity,
LogicalName = "tec_new_mtfmtir",
};
RetrieveEntityResponse retrieveBankAccountEntityResponse = (RetrieveEntityResponse)service.Execute(retrieveBankAccountEntityRequest);
//return retrieveBankAccountEntityResponse.LogicalName.ToString();
}
If your optionset is a global optionset, you can retrieve it using the RetrieveOptionSetRequest message. Here is a bit of sample code
RetrieveOptionSetRequest retrieveOptionSetRequest =
new RetrieveOptionSetRequest
{
Name = _globalOptionSetName //Put your optionsetname here
};
// Execute the request.
RetrieveOptionSetResponse retrieveOptionSetResponse =
(RetrieveOptionSetResponse)_serviceProxy.Execute(
retrieveOptionSetRequest);
OptionMetadata[] optionList =
((OptionSetMetadata) retrieveOptionSetResponse.OptionSetMetadata).Options.ToArray();

Object reference not set to an instance of an object error

I have Default.aspx and Upload.aspx.
I'm passing Id through query string to default.aspx(like:http://localhost:3081/default.aspx?Id=1752).In default page i have a link button to open the upload.aspx to upload file.When i use the Request.QueryString["Id"] in upload.aspx,it is showiing error as "Object reference not set to an instance of an object".I'm dealing with RadControls.
To open when i click a link(OnClientClick="return ShowAddFeedBackForm()") i have code like:
<script>
function ShowAddFeedBackForm() {
window.radopen("Upload.aspx", "UserListDialog");
return false;
}
</script>
I'm using detailsview in upload page with a textbox and a fileupload control.
code to bind when a file upload in upload.aspx
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
string qString = Request.QueryString["Id"].ToString();
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
//string qString = Request.QueryString["Id"].ToString();
//int Projectid = Convert.ToInt32(Session["ProjectId"]);
ProTrakEntities objEntity = new ProTrakEntities();
TextBox txtTitle = DetailsView1.FindControl("txtTask") as TextBox;
//RadComboBox cmbStatus = DetailsView1.FindControl("cmbStatus") as RadComboBox;
//var id = (from project in objEntity.Projects where project.ProjectId == Projectid select project).First();
RadComboBox cmbTaskType = DetailsView1.FindControl("cmbTasktype") as RadComboBox;
//RadComboBox cmbTaskPriorty = DetailsView1.FindControl("cmbPriority") as RadComboBox;
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
int pID = Convert.ToInt32(guid.ProjectId);
ProjectFeedback objResource = new ProjectFeedback();
objResource.ProjectId = pID;
objResource.Subject = txtTitle.Text;
objResource.Body = Description;
objResource.CreatedDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
objResource.FeedbackType = cmbTaskType.SelectedItem.Text;
objEntity.AddToProjectFeedbacks(objResource);
objEntity.SaveChanges();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
}
}
Getting error at querystring statement-"Object reference not set to an instance of an object"
The query string is not inherited when you open a new page. You have to include the id in the URL, i.e. Upload.aspx?id=1752.
Edit:
A simple solution would be to just copy the search part of the page URL:
window.radopen("Upload.aspx" + document.location.search, "UserListDialog");
However, typically you would use the id value that you picked up from the query string in the server side code and generate client code to use it.
I am not sure but if I had to guess I would question whether the window object has been instantiated at the time you call radopen in the script section of your page. You should put a msgbox before the call window.radopen() call to print the contents of the window object if it is null that is your problem otherwise this will take more digging. Just my two cents.
I also noted that if the guid query returns no results the call to .First() will cause this error as well. Just another place to check while researching the issue.
There is one last place I see that could also throw this error if the objEntities failed to construct and returned a null reference then any call to the properties of the object will generate this error (i.e objEntitiey.Projects):
ProTrakEntities objEntity = new ProTrakEntities();
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
This error is occurring because, as the other answerer said, you need to pass the ID to the RadWindow since the RadWindow doesn't know anything about the page that called it. You're getting a null reference exception because the window can't find the query string, so it's throwing an exception when you try to reference .ToString().
To get it to work, make your Javascript function like this:
function ShowAddFeedBackForm(Id) {
window.radopen(String.format("Upload.aspx?Id={0}", Id), "UserListDialog");
return false;
}
In the codebehind Page_Load event of your base page (ie, the page that is opening the window), put this:
if (!IsPostBack)
Button.OnClientClick = string.Format("javascript:return ShowAddFeedBackForm({0});", Request.QueryString["Id"]);
Of course, Button should be the ID of the button as it is on your page.

recovering from missing session state in ASP.NET MVC with Telerik Ajax

I have a webpage which includes a telerik grid in ajax mode. The data for the grid is constructed in the controller action used to serve the view, and then stored in the session. 90% of the time its available to the ajax method used to populate the grid. And sometimes its not, which is odd. Some sort of race condition ?
public ActionResult EditImage(int productModelId, int revision)
{
ViewBag.Current = "Edit";
//Unit of work and repo generation removed from brevity
var modelToEdit = prodModelRepo.Where(p => p.ProductModelID == productModelId && p.Revision == revision).FirstOrDefault();
var vmie = new VMImageEdit(modelToEdit)
{
//init some other stuff
};
Session["vmie"] = vmie;
return View(vmie);
}
Now the telerik contorol will post back to _EISelect in order to populate its grid
// Ajax Actions for EditImage
[GridAction]
public ActionResult _EISelect()
{
var vmie = (VMImageEdit) Session["vmie"];
return View(new GridModel(vmie.Colours));
}
So if my session object is null, how can I recover - I guess I need the productModelId and Revision parameters from the original EditImage call. Are they available in the _EISelect in any way - its posted to, and the post contains nothing useful.
Oh to make this possibly harder, this page will be displayed via an inline frame.
The answer lies in the telerik ajax databinding - this can be used to pass arbitrary data in the querystring
.Select("_EISelect", "AdminProduct", new { productModelId = Model.ProductModelId, revision = Model.Revision})
which can be recovered in _EISelect as parameters. Simples.

Is there a better way to get ClientID's into external JS files?

I know this has been asked before, but I've found a different way to get references to controls in external JS files but I'm not sure how this would go down in terms of overall speed.
My code is
public static void GenerateClientIDs(Page page, params WebControl[] controls) {
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in controls) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
if (!page.ClientScript.IsClientScriptBlockRegistered("Vars")) {
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "Vars", script.ToString());
}
}
This was I can reference the id of the aspx page in my JS files.
Can anyone see any drawbacks to doing things this way? I've only started using external JS files. Before everything was written into the UserControl itself.
Well, the method can only be used once in each page, so if you are calling it from a user control that means that you can never put two of those user controls on the same page.
You could store the control references in a list until the PreRender event, then put them all in a script tag in the page head. That way you can call the method more than once, and all client IDs are put in the same script tag.
Something like:
private const string _key = "ClientIDs";
public static void GenerateClientIDs(params WebControl[] controls) {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
if (items == null) {
page.PreRender += RenderClientIDs;
items = new List<WebControl>();
}
items.AddRange(controls);
HttpContext.Current.Items[_key] = items;
}
private static void RenderClientIDs() {
Page page = HttpContext.Current.Handler As Page;
List<WebControl> items = HttpContext.Current.Items[_key] as List<WebControl>;
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
foreach (WebControl c in items) {
script.AppendLine(String.Format("var {0} = '#{1}';", c.ID, c.ClientID));
}
script.AppendLine("</script>");
page.Head.Controls.Add(new LiteralControl(script));
}
Check this out: http://weblogs.asp.net/joewrobel/archive/2008/02/19/clientid-problem-in-external-javascript-files-solved.aspx
Looks like it takes care of the dirty work for you (something like Guffa's answer). It generates a JSON object (example) containing server IDs and client IDs, so you can do something like this in your JavaScript:
var val = PageControls.txtUserName.value;

Resources