Populate ComboboxList client side using ajax - c#

Ok so i'm using this piece of AJAX code
xhr2 = new XMLHttpRequest();
xhr2.open('POST', '/AllPoints.aspx', false);
xhr2.setRequestHeader('kml_file', path);
And what I'm doing server side is this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.Headers["kml_file"]))
{
DataTable dt = GetDataSet().Tables[0];
CBList_Pontos_Repetidos.DataSource = dt;
CBList_Pontos_Repetidos.DataTextField = dt.Columns[1].ToString();
CBList_Pontos_Repetidos.DataValueField = dt.Columns[0].ToString();
CBList_Pontos_Repetidos.DataBind();
}
}
}
And everything runs fine and by debugging I can see all the code is being executed, problem is, it's all server side and there's no actual postback, async or not, so nothing is shown client-side, I can only see it server side.
I've been around and around this and I can't seem to figure out the solution, any help?
PS: I've edited all the unnecessary strings of code so you can understand it better.
Thanks in advance.

I would have a look at accessing asp.net page methods through ajax. Here's a helpful link

Related

Windows 8.1 ScriptNotify not working

I am stumped on an issue with webview and scriptnotify
Server chap has put the following code in the web page:
javascript(alert) and javascript(confirm)
I put in a Debug Writeline to even see if the method is being called but it is not.
I can confirm that the https://webpage.com is in the Manifest as an accepted Uri.
Here is my code
XAML
<Grid>
<WebView x:Name="webView1" HorizontalAlignment="Stretch" ScriptNotify="MyWebView_ScriptNotify" VerticalAlignment="Stretch" />
</Grid>
C#
public TeamPage()
{
this.InitializeComponent();
webView1.ScriptNotify += MyWebView_ScriptNotify;
//other stuff
}
async void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
Debug.WriteLine("in here");
var jsScriptValue = e.Value;
MessageDialog msg = new MessageDialog(jsScriptValue);
var res = await msg.ShowAsync();
}
As said, the MyWebView_ScriptNotify is not even called?? There does not seem to be much examples on this issue so any help would be much appreciated. Thanks.
ScriptNotify does not fire on javascript alert or confirm.
It fires if the webpage does the following in JavaScript:
window.external.notify('some value');
Also see description and sample in MSDN
Edit: If you need to get notified about alert and confirm you could do something like this:
// do this after initialization of the webview
this.MyWebView.NavigationCompleted += MyWebView_NavigationCompleted;
...
async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// this will override the alert function with a function calling
// the window.external.notify function
// you should be able to do the same with confirm
string inject =
#"window.alert = function(arg) {
window.external.notify(arg);
};";
await MyWebView.InvokeScriptAsync("eval", new List<string>() { inject });
}
Talked with the server chap and it looks like we can not do it in my instance. Dennis' solution is the answer if someone is looking for a similar solution, but if you want to use alert and confirm, then its not possible as far as I can tell. That said, happy to be corrected and update this answer if corrected.

ASP.NET Web Application using Watin

I'm experimenting with Watin in Visual Studio 2012 (C#), but I cannot seem to get anything to work. Currently I have two text boxes in an aspx page (txtbox1 and txtbox2). I am trying to have Watin automatically input numbers into these two text boxes and then click on the "Calculate" button which will add the two numbers together. I installed the Watin framework and added the Watin.Core dll as a reference.
Here is my code for so far in my .aspx page:
using WatiN.Core;
[STAThread]
protected void Page_Load(object sender, EventArgs e)
{
IE ie = new IE("http://localhost:5243/Addition.aspx");
ie.TextField(Find.ByName("txtbox1")).TypeText("1");
ie.TextField(Find.ByName("txtbox2")).TypeText("2");
ie.Button(Find.ByValue("Calculate")).Click();
}
I keep getting the error message stating:"The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer". Do you know what can cause this?
Thanks for any help in advance!
First of all, you're trying to automate Internet Explorer from the server-side ASP.NET code. This is generally a bad idea. This article describes the implications of doing this with Office, the same concerns apply to Internet Explorer.
That said, to succeed with what you're trying to do, you'd need to run an STA thread on the server side, and run your Watin code inside that thread. Placing [STAThread] on your ASP.NET Page_Load handler won't automagically make this happen.
Here is how it can be done, but again, doing so on the server is not recommended:
protected void Page_Load(object sender, EventArgs e)
{
RunOnStaThread<object>(() =>
{
IE ie = new IE("http://localhost:5243/Addition.aspx");
ie.TextField(Find.ByName("txtbox1")).TypeText("1");
ie.TextField(Find.ByName("txtbox2")).TypeText("2");
ie.Button(Find.ByValue("Calculate")).Click();
return null;
});
}
static T RunOnStaThread<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
var thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
try
{
return tcs.Task.Result;
}
finally
{
thread.Join();
}
}

How to detect page refresh in .net

I have a Button_click event. While refreshing the page the previous Postback event is triggering again. How do I identify the page refresh event to prevent the Postback action?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
This article could be of help to you
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this
http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
This worked fine for me..
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
Simple Solution
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1 without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loaded parameter of the query string.
Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState (assuming SessionState is enabled) and the value of the loaded QueryString parameter
the window.onbeforeunload event listener
keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
cookies
If someone does come up with a solution, I'd love to hear it.
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}

Delay in event in code behind file

In my application I have a button to save some information. However, I would like to have a delay in the code before the last line is executed, so that the user could read the message that shows up before he gets redirected to the new page.
I know that doing this isn't at all an optimal way, but by some reasons (time, for example) I want to do it anyway.
So is it possible and if so, how could I do it?
Thanks in advance!
protected void SaveButton_Click(object sender, EventArgs e) {
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
Response.Redirect(String.Format("~/Edit.aspx?id={0}", movie.MovieID), false);
}
You need to do this on the client side. One alternative is this:
Define a Javascript function in the page called redirect as so:
function redirect(url)
{
setTimeout(function(){window.location.href=url;} ,2000);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
ClientScript.RegisterStartupScript(this.GetType(),"somekey","redirect('"+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+"');");
}
This will be easy if you are using Javascript. Use javascript will boost performance
Button_Click
{
string js ="<script type='text/javascript'>setTimeout(function()window.location.href="+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+";} ,2000);</script>"
ScriptManager.RegisterStartupScript(Me.Page, GetType(Page), "js", js, False)
}
possible duplicate of
asp.net delay before response redirect

Firing a server-side method via PageMethod

I wrote a JavaScript function that fires when the user clicks OK in a RadConfirm dialog. This is supposed to trigger a JavaScript callback to the server to delete a record from the database. This may not be the best architecture (I can think of other ways to accomplish my goals) but I'm trying to struggle through this as a learning exercise. Below is the code I've written thus far. I think I've gotten most of it correct.
This Javascript function:
function confirmCallBackFn(arg) {
if (arg == true) {
PageMethods.RemovePackagePageMethod();
}
else {
}
}
Should invoke the following WebMethod on the server:
[WebMethod()]
public static void RemovePackagePageMethod(object sender, EventArgs e)
{
Inventory inv = new Inventory();
inv.RemovePackage();
}
Which in turn should execute the following method:
private void RemovePackage()
{
SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();
var boxes = from p in db.Packages
where p.PackageID == Convert.ToInt32(RadGrid1.SelectedValues["PackageID"].ToString())
select p;
foreach (var box in boxes)
{
db.Packages.DeleteOnSubmit(box);
}
try
{
db.SubmitChanges();
RadGrid1.Rebind();
}
catch (Exception ex)
{
RadWindowManager1.RadAlert("System error deleting package", 200, 200, "exception", null);
}
}
Everything looks good to me and seems to be consistent with the posts I've read on this site and others about using PageMethod to fire code on the server. However, it's failing to execute the deletion in the final method (which I've tested in isolation). Can someone spot where I went wrong?
You are trying to use the RadGrid1 control in the RemovePackage method, but you are calling the method from a web method, so there is no instance of the Page class, and thus there is no RadGrid1 control.
You would have to send the id of the record that you want to delete from the client code to the web method, and from there along to the RemovePackage method.
Also, you can't rebind the RadGrid1 control to make the changes appear in the page. The web method call is not a page request, so there is no page response that can contain the updated grid. You would have to update the grid in the client code.
Try making the RemovePackage method Public (Friend may work too) instead of private and then try.

Categories