How to call Javascript from C# PageLoad? - c#

I want to ask How to call javascript from C# page load.
My Javascript is
function Hide(lst) {
if (document.getElementById) {
var tabList = document.getElementById(lst).style;
tabList.display = "none";
return false;
} else {
return true;
}
}
and want to call from pageload
if (dtSuperUser(sLogonID).Rows.Count < 1)
{
//Call Javascript with parameter name tablist
}
thanks

Actually, you can use pageOnload event to do so.
Like this.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'block'</script>");
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "show", "<script>document.getElementById('Your element').style.display = 'hidden'</script>");
}
}

String csName = "myScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
cs.RegisterClientScriptBlock(csType, csName,
string.Format("Hide({0})", lst.ClientID));
}

RegisterStartupScript("Hide", string.Format(#"if (document.getElementById) {
var tabList = document.getElementById('{0}').style;
tabList.display = 'none';
return false;
} else {
return true;
}",lst));
Or if you already have the Javascript function rendered in the Markup
RegisterStartupScript("Hide",string.Format("Hide('{0}');",lst));

Are you using webforms or MVC? If using webforms check:
http://msdn.microsoft.com/en-us/library/Aa479011
Page.RegisterStartupScript("MyScript",
"<script language=javascript>" +
"function AlertHello() { alert('Hello ASP.NET'); }</script>");
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";

Related

C#, ASP.NET: how to get a confirm message box from server side code when a condition is met

I have a button in my page which is used to save data of gridview which is dynamically populated. Before saving I want to check some condition. The javascript function is as follows:
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("This will completely delete the project. Are you sure?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="Confirm()"></button>
The code behind is as follows:
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
{
MyAlert("No clicked");
}
}
else
{
MyAlert("No Text found.");
}
}
Now the problem is since I have the function Confirm() in the onClientClick event, the confirm dialog appears the moment the user clicks the button, instead it should appear only when a string is found in txtID.
I tried to modify the code by removing the onClientClick event as follows:
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" ></button>
protected void lnkBtn_Click(object sender, EventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
if (confirmValue == "No")
{
MyAlert("No clicked");
}
}
}
Here also it is not working properly. The confirmValue is getting the value but using it only during the subsequent click of the button. It is not passing value stored during the present click event instead the previously stored value is passed to if block. Please help to find what should I do get it right.
Thanks.

Page Index Changing do not works properly

Am using vs-2010 with c#, In my application i want to clear a label text in the Page index changing Event. Here is my code
protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDetails.PageIndex = e.NewPageIndex;
// BindGrid(ddlJournal.SelectedItem.Text);
DataSet ds = new DataSet();
ds = ViewState["ds"] as DataSet;
if ((Convert.ToString(ViewState["Template"]) != null
|| (Convert.ToString(ViewState["Template"]) != "")))
{
if ((Convert.ToString(ViewState["Template"]) == "T1"))
{
GridData("T1");
}
else if ((Convert.ToString(ViewState["Template"]) == "T2"))
{
GridData("T2");
}
else if ((Convert.ToString(ViewState["Template"]) == "T3"))
{
GridData("T3");
}
}
else
{
BindGrid(ddlJournal.SelectedItem.Text);
}
btnupdate_Click(sender, e);
lblError.Text = "";
lblSuccess.Text = "";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "call()", true);
}
My problem is the page index are changing properly but the label values do not be empty , what is the problem in my application and how can i fix this.
Thanks in advance .
First of all your code is a mess and do not say thanks here on STACKOVERFLOW and second of all you are calling a method is your gvDetails_PageIndexChanging handler that calls btnupdate_Click(sender, e); do you set a value for your labels there?

call OnClientClick and Onclick together in c# Button Event

I have a Asp.Net c# application in which, having Logout Button on mAsterpage.
I am trying to alert confirmation window on click of LogOut. If i choose Yes, then I will redirect it into Log-in Page.
So I have tried below. OnClient Click I called below JavaScript Function.
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On Button Click I have wriiten Below code.
protected void ImgbtnLogOut_Click(object sender, ImageClickEventArgs e)
{
try
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Session.Clear();
Session.Abandon();
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
//Server.Transfer(ConfigurationManager.AppSettings["LogoutURL"].ToString());
}
else
{
//Do Nothing
}
}
catch (Exception ex)
{
}
finally
{
}
}
I am getting an error Unable to evaluate Expression, The code is Optimized....error in below line. And Page is not being redirected to required page.
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
can anyone please suggest, how can i achieve that.
This confirm box help you to get correct response with having Ajax.
java script code for geting confirm value.
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to proceed continue ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On C# Code for geting exect data.
string confirmValue = Request.Form["confirm_value"];
string[] Value_Confirm = confirmValue.Split(',');
if (Value_Confirm[Value_Confirm.Length-1] == "Yes")
{}
or check here : http://www.codeproject.com/Answers/1070495/Ask-yes-no-cancel-window-in-csharp#answer6

ICallbackEventHandler, RaiseCallbackEvent not firing

I have the following Javascript:
function processText(n)
{
CallServer("1" + n.id + "&" + n.value, "");
}
function ReceiveServerData(arg, context)
{
alert(arg);
}
With this for my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbRef = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackscript = "function CallServer(arg, context) {" + cbRef + "; }";
cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackscript, true);
if (Request.QueryString["stationID"] != null)
{
isIndividual = true;
stationID = Request.QueryString["stationID"];
EncodeDecode objServers = new EncodeDecode(HttpContext.Current.Server.MapPath("~/App_Data/"));
if (!IsPostBack)
{
List<IServerConfig> serverConfig = objServers.GetServerConfiguration(stationID);
Session["ServerConfig"] = serverConfig;
Session["dctPropertyControls"] = new Dictionary<string, PropertyObj>();
}
BindDynamicControls(Session["ServerConfig"] as List<IServerConfig>);
}
}
public void RaiseCallbackEvent(String eventArgument)
{
int iTyped = int.Parse(eventArgument.Substring(0, 1).ToString());
if (iTyped != 0) //Process Text Fields
{
string controlName = eventArgument.Substring(1, eventArgument.IndexOf("&")).ToString();
string controlValue = eventArgument.Substring(eventArgument.IndexOf("&")).ToString();
//Txtid += -1;
Dictionary<string, PropertyObj> dctPropertyObj = Session["dctPropertyControls"] as Dictionary<string, PropertyObj>;
PropertyObj propertyObj = dctPropertyObj[controlName];
propertyObj.property.SetValue(propertyObj.owner, controlValue, null);
this.sGetData = "Done";
}
}
public String GetCallbackResult()
{
return this.sGetData;
}
processText gets fired and works, however RaiseCallbackEvent never fires. Any ideas?
Apparently, any sort of validation error will cause this, though the page will never tell you about it. In my case, I had two datalists on the page with the same id. I had to debug the javascript and read the xmlRequest to see the error.
Sorry if replying late but may help others..
ValidationRequest="false" at .aspx page may sort out this unidentified problem.

How to prevent my textbox from clearing text on postback.

I have a pretty interesting dilemma that is giving me a hurricane of a headache. I've seen a similar question asked here, but the user posted no code, so it was unresolved. This is a asp.net, sql server, and c# app.
In my application, I use JavaScript to display dummy data in a TextBox to entertain the user while a long process is running. (please note, this is a project, not a professional app).
The problem is, once the app is done executing, the app (I believe) refreshes the page and clears the TextBox. I want to prevent this from happening and continue to display the text after the program is completed.
My question is, where in the following code is the page being refreshed? How can I re-code it to prevent the text from being cleared?
I know there is no issue with the JavaScript or the .aspx page. I have not set or programmed any property to clear the text. If anyone could shed light on the issue, I would greatly appreciate it. If you need more code from me please let me know. I will be very active on this page until it is resolved. Thanks again!
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{ }
protected void btnExit_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
btnExit.Visible = true;
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = false;
SuccessLabel.Visible = true;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
private void Initialize()
{
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
if (!IsPostBack)
{
FileNamePrefix = bf.FileNamePrefix;
NextBatchNum = bf.NextBatchNum;
BatchesCreatedLbl.Text = (int.Parse(NextBatchNum) - 1).ToString();
if (bf.CheckLocalForNewBatch() == true)
{
NoBatchesToProcessLbl.Visible = false;
BatchesToProcessLbl.Visible = true;
if (int.Parse(NextBatchNum) >= 50)
{
ErrorLabel.Text += ErrorLabel.Text + OverBatchLimitStr;
ErrorLabel.Visible = true;
PutFTPButton.Enabled = false;
}
else
{
bf.ReadyFilesForTransmission();
ErrorLabel.Visible = false;
PutFTPButton.Enabled = true;
List<string[]> detStream = bf.GetBatchStream("DET");
List<string[]> hdrStream = bf.GetBatchStream("HDR");
OrdersInfoDiv.Visible = true;
DataTable dt = new DataTable();
dt.Columns.Add("ORDER NUMBER");
dt.Columns.Add("LINE NUMBER");
dt.Columns.Add("ITEM NUMBER/ISBN");
dt.Columns.Add("DESCRIPTION");
dt.Columns.Add("QUANTITY");
dt.Columns.Add("SHIPPING");
Dictionary<string, string> orderShip = new Dictionary<string, string>();
foreach (string[] hdrItems in hdrStream)
{
orderShip.Add(hdrItems[0], hdrItems[2]);
}
foreach (string[] detItems in detStream)
{
List<string> detLineList = new List<string>(detItems);
detLineList.Add(orderShip[detItems[0]]);
detLineList.RemoveAt(13);
detLineList.RemoveAt(12);
detLineList.RemoveAt(11);
detLineList.RemoveAt(10);
detLineList.RemoveAt(9);
detLineList.RemoveAt(8);
detLineList.RemoveAt(7);
detLineList.RemoveAt(4);
detLineList.RemoveAt(2);
detLineList[1] = detLineList[1].TrimStart('0');
detLineList[4] = detLineList[4].TrimStart('0');
dt.Rows.Add(detLineList.ToArray());
}
BatchDetails.DataSource = dt;
BatchDetails.DataBind();
}
}
else
{
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
}
}
}
}
Yes. You will have to determine the state of your calculation and populate the control inside Page_Load in the case where IsPostBack is true:
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// re-populate javascript-fill UI
} else {
}
Initialize();
}
You can probably also move Initialize() into the else clause as well.
Since you are handling the button click server side (I'm assuming the problem is happening once the user clicks the button?) there has to be a postback to handle it.
You could try putting your button and label into an updatepanel control - it uses AJAX to refresh its contents.
See this page for more information on updatepanels.

Categories

Resources