I tried all possible ways to add javascript code to my dynamically created control a date textbox but it is not working. I need to add multiple scripts like searchable dropdownlist and datepicker for date textbox. I am creating control on Page_Init and then attaching javascript on Page_Load but it is not working. Can somebody help, please? Thanks.
protected void Page_Init(object sender, EventArgs e)
{
CreateControls();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (fieldtype == "date")
{
string javaScriptString = #"function attachJSScript() {";
javaScriptString += #"$('#<%= " + str + ".ClientID %>').datepicker({ dateFormat: 'dd/mm/yy' }).val();";
javaScriptString += #"}";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "attachJSScript", javaScriptString, true);
}
}
}
}
When I view the page source, it shows
<script type="text/javascript">
//<![CDATA[
function attachJSScript() {$('#<%= txt_1_date_yes.ClientID %>').datepicker({ dateFormat: 'dd/mm/yy' }).val();}//]]>
</script>
I added this code for dropdownlist dynamically created control but it is not working either. Same code I used for the controls in aspx pages and that works.
Related
I have a LinkButton in masterpage and on click of LinkButton , I am redirecting to, say, Page1.aspx . On Page1.aspx , I have a button1. On click of that button1, I am opening new window, not affecting data of the Page1.aspx.
But when I click on LinkButton of masterpage, redirecting to Page1.aspx and from code behind,clicking button1 , Page1.aspx 's data gets changed.
How to prevent this. I am providing my code.
LinkButton on Masterpage :
<asp:LinkButton ID="lnkAppointMent" runat="server" OnClick="lnkAppointMent_Click"><span>Appointment Scheduler </span></asp:LinkButton>
click Event of LinkButton :
protected void lnkAppointMent_Click(object sender, EventArgs e)
{
Session["PhoneCenter"] = "Appointment";
Response.Redirect("PhoneMessage.aspx");
}
PageLoad of redirecting page(PhoneMessage.aspx) :
protected void Page_Load(object sender, EventArgs e)
{
fillCustomTypeMessages();
if (!Page.IsPostBack)
{
.
.
.
else if (Session["PhoneCenter"].ToString() == "Appointment")
{
btnScheduleAppointments_Click(btnScheduleAppointments, null);
}
.
.
.
Button on PhoneMessage.aspx :
<div style="float: right; padding-right: 120px">
<asp:Button ID="btnScheduleAppointments" runat="server" OnClick="btnScheduleAppointments_Click"
CssClass="button" Text="Schedule Appointments" ToolTip="Open appointment scheduler" />
</div>
RaisPostBack method on PhoneMessage.aspx :
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
try
{
base.RaisePostBackEvent(source, eventArgument);
}
catch (Exception ex)
{
}
.
.
p.s : when I click on btnScheduleAppointment , source will be Schedule Appointments and if I click on lnkAppointMent , source will be <span>Appointment Scheduler </span> even if I am calling btnScheduleAppointment on click of lnkAppointMent.
Click event of button :
protected void btnScheduleAppointments_Click(object sender, EventArgs e)
{
if (!Permissions.checkPermissions(Session["employeeloggedin"].ToString(), "PHMSGVMD"))
{
ScriptManager.RegisterStartupScript(this, Page.GetType(), "OnLoad", "alert('You must have the Phone Messages: View and Modify permission to schedule appointments!')", true);
}
else
{
string script = String.Format("openNewWin('" + "phonescheduler.aspx" + "')");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "openNewWin", script, true);
}
}
Script :
function openNewWin(url)
{
alert(url);
var open_link = window.open('', '_blank');
open_link.location = url;
}
Any clarification needed. Please comment.
It took me some time to simulate your problem. Have you tried to modify the LinkButton href or atributes after the Page1.aspx has been loaded?
I am assuming your Page1.aspx is your PhoneMessage.aspx, so when you click lnkAppointMent from the master page, it goes to "PhoneMessage.aspx" and execute the method, then if you click it again it will only post back instead of do what it did before, basically, you you need to redirect to "PhoneMessage.aspx" again.
So why dont you modify the part like this:
else if (Session["PhoneCenter"].ToString() == "Appointment")
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "NoExec", String.Format("document.getElementById('lnkAppointMent').href=window.location.href;"), true);
btnScheduleAppointments_Click(btnScheduleAppointments, null);
}
That would make the link redirect to the Page1.aspx again, and do the same without postback. It is not the most elegant solution, but it does the job in your case. Just make sure to have Session["PhoneCenter"] = "Appointment";
So it is not the answer to your question but I think is a solution to your problem.
It worked for me, I hope It helps! Let me know what you think.
I have set dropdown enable set to false in one button click and i will set enable="true" is not working in page load
here is my aspx
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" />
Here is my click event:
protected void btnTemplate_click(object sender, EventArgs e)
{
check.Value = "1";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Load_functions()", true);
//txtAddJournal.Attributes.Add("Style", "display:block");
//btnUpload.Attributes.Add("Style", "display:block");
//if (fileuploader.HasFile)
//{
try
{
string Filename = Path.GetFileName(fileuploader.FileName);
//fileuploader.SaveAs(Server.MapPath("~/") + Filename);
// fileuploader.SaveAs(Server.MapPath("D:\\Req Sep16\\") + Filename);
OleDbConnection myconnectionini = default(OleDbConnection);
OleDbDataAdapter mycommandini = default(OleDbDataAdapter);
//if (fileuploader.PostedFile.FileName.EndsWith(".xls") == false & fileuploader.PostedFile.FileName.EndsWith(".xlsx") == false)
//{
// // lbl_Error.Text = "Upload only excel format";
// Response.Write(#"<script language='javascript'>alert('Upload only excel format');</script>");
// return;
//}
//else
//{
gvDetails.DataSource = null;
string pathToSave = HttpContext.Current.Server.MapPath("~/UploadFiles/") + "Copy of Database_HBM";
//fileuploader.PostedFile.SaveAs(pathToSave);
//strFilePath = "D:\\Files\\" + fileuploader.FileName;
string constrini = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + pathToSave + ";Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
// DataTable dt = new DataTable();
myconnectionini = new OleDbConnection(constrini);
mycommandini = new OleDbDataAdapter("select * from [Sheet1$]", myconnectionini);
ds = new DataSet();
mycommandini.Fill(ds);
gvDetails.DataSource = ds.Tables[0];
gvDetails.DataBind();
ddlJournal.SelectedIndex = -1;
ddlJournal.Enabled = false;
//ddlJournal.Attributes.Add("disabled", "disabled");
//}
}
catch (Exception ex)
{
string msg = ex.Message;
}
//}
}
And my page load event is
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
// ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>headerLock();</script>", true );
if (!IsPostBack)
{
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
ddlJournal.Enabled = true;
}
}
button :
<asp:Button ID="btnUpload" runat="server" Text="Template 1" OnClientClick="return Validate();"
OnClick="btnTemplate_click" CssClass="btn" />
but still my dropdown list is disable.
suggest me get a solution
thanks in advance
You can set dropdown list Enabled false from its control only like this
<asp:DropDownList ID="ddlJournal" runat="server" OnSelectedIndexChanged="ddlJournal_SelectionChanged" AutoPostBack="true" CssClass="drop" Enabled="false"/>
And the rest code should work fine.
Please mark it helps
Understand that your if-else condition in Page_Load() method is the main culprit. You're always setting ddlJournal.Enabled = true, no matter what. Seems like you didn't properly understand the concept of IsPostBack. ddlJournal is supposed to be disabled when IsPostBack is true, because that's what you want. Otherwise, it's supposed be enabled.
This is a very concise explanation about what IsPostBack is:
Postback in an event that is triggered when a action is performed by a contol on a asp.net page. for eg. when you click on a button the data on the page is posted back to the server for processing.IsPostback is normally used on page _load event to detect if the page is getting generated due to postback requested by a control on the page or if the page is getting loaded for the first time.
[a comment from http://forums.asp.net/t/1115866.aspx?What+is+IsPostBack ]
So based on that, you should change your code like the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Grid", "headerLock();", true);
if (!IsPostBack)
{
//When IsPostBack is false, ddlJournal should be enabled
Bindddl();
BindGrid(null);
ddlJournal.Enabled = true;
}
else
{
//Else, IsPostBack is true, so, ddlJournal should be disabled
ddlJournal.Enabled = false;
}
}
Also, you don't need this in your btnTemplate_click() method since you're doing this on page load:
ddlJournal.Enabled = false;
protected void Button1_Click(object sender, EventArgs e)
{
if (count > 100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById(\" <%=TextBox1.ClientID%>\").value=\"1\"; alert(document.getElementById(\"<%=TextBox1.ClientID %>\").value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
Here I want to set the value of the textbox by clicking the button event and oly that condition is true.So I cant call that function from source.actually that function gets called but the textbox value doesnt set..I really dont understand where is the problem..
protected void Button1_Click(object sender, EventArgs e)
{
if(count>100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById('" + TextBox1.ClientID + "').value=\"1\"; alert(document.getElementById('" + TextBox1.ClientID+ "').value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
}
You need to concatenate the TextBox1.ClientID with your javascript string. The code you have will get rendered to the page as is, look at the output of your rendered page with view source, you will see the string '<%= TextBox1.ClientID =%>' not the expected ID. Keep in mind that the inline display expression <%= =%> is equivalent to a server Response.Write().
how to call this javascript function from asp.net codebehind pageload..
<script type="text/javascript">
function abc() {
alert("Hello! I am an alert box!");
}
</script>
Is it possible to pass an integer array in to javascript function from asp.net codebehind pageload?
Try below code :
protected void Page_Load(object sender, EventArgs e)
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc();", true);
}
1. Update > Passing string parameter :
protected void Page_Load(object sender, EventArgs e)
{
var message = "hi";
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc('" + message + "');", true);
}
JavaScript Method with string parameter :
function abc(message) {
alert(message + ", I am an alert box!");
}
2. Update > Passing string parameter and numeric array to JS method:
protected void Page_Load(object sender, EventArgs e)
{
int[] numbers = { 10, 20, 30 };
string serializedNumbers = (new JavaScriptSerializer()).Serialize(numbers);
var message = "hi";
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "abc('" + message + "', " + serializedNumbers + ");", true);
}
JavaScript Method with string and numeric array parameters:
function abc(message, numbers) {
alert(message + ", I am an alert box!");
for (var i = 0; i < numbers.length; i++) {
alert(numbers[i]);
}
}
Regular Page
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "abc" + UniqueID, "abc();", true);
}
Ajax Page
You need to use ScriptManager if you use ajax.
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"abc" + UniqueID, "abc();", true);
}
Try
Dim script As String = String.Format("abc()", "")
ScriptManager.RegisterClientScriptBlock(Me, GetType(Page), UniqueID, script, True)
Or simply
ClientScript.RegisterStartupScript(GetType(), "abc", "alert('Hello! I am an alert box!')", true);
You can't call a JavaScript function from the codebehind, but you can return a response that includes JavaScript that invokes the function when the page loads in the browser. Just make sure that your page includes
<script type="text/javascript">
function abc() {
alert("Hello! I am an alert box!");
}
abc();
</script>
That could be either as part of the ASPX page or you could register it as a script block in the codebehind.
This is my Code, After Server.Execute() my popup does not show.
protected void Generate_cola_letter(object sender, EventArgs e)
{
try
{
Server.Execute("../ABC.aspx");
}
catch (Exception exp)
{
}
finally
{
ScriptManager.RegisterStartupScript();
}
Are you trying to create a Message box?
this is an example of a message box in asp.net
string script = "alert(\"Your Message.\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);