Whats wrong in this asp.net code? Textbox value doesnt set - javascript

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().

Related

Add JavaScript function to a dynamically created control

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.

Show message only on first access to the web page in c#

With this code I show JavaScript alert message box in ASP.Net from server side using C#.
But I need show the message only on first access to the web page, how to do resolve this ?
Please help me.
My code below, thank you in advance.
protected void Page_Load(object sender, EventArgs e)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
You need to check that the page is not posting back before you display your alert:
if (!IsPostBack)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Updates:
You can create a cookie to track the alert so it does not display after displaying during the initial page load:
private bool Alerted()
{
if (Request.Cookies["alerted"] != null)
return Server.HtmlEncode(Request.Cookies["alerted"].Value) == "true";
else
{
Response.Cookies["alerted"].Value = "true";
Response.Cookies["alerted"].Expires = DateTime.Now.AddDays(10);
return false;
}
}
Usage:
if(!Alerted())
{
// alert script here
}

Dropdownlist "Enable true" is not working Asp.net

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;

When I use window.location.href ,then my another function not calling .Following is my javascript code

I am using Following code..
When I click on the link, the javascript Hello() function is invoked
I want to use window.location.href
But when I use this the following __doPostBack('Button2_Click'), it does not work.
But when remove window.location.href from the following code then __doPostBack('Button2_Click') does work.
<script type="text/javascript">
function Hello(clicked_id) {
var abc = "http://localhost:2621/OrgChart.aspx?id" + clicked_id;
window.location.href = abc;
__doPostBack('Button2_Click');
return false;
}
</script>
<a id="A1" href="javascript:Hello();">LINK</a>
This is my code behind code...
public partial class WebForm17 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);//This is important to make the "__doPostBack()" method, works properly
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
Button2_Click(this, new EventArgs());
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Method called!!!";
EmpInfo emp = new EmpInfo();
DA_EmpInfo da_emp = new DA_EmpInfo();
List<EmpInfo> lei = da_emp.GetAllEmployeeInfoByEmpId("MJ-IB-1");
DetailsView1.DataSource = lei;
DetailsView1.DataBind();
}
}
I guess, __doPostBack is making a request to the server and you break it by using window.location.href = abc;.
You should use some callback from this request to redirect to your url.
try to use setTimeOut function
setTimeout(function () {
window.location.href = abc;
}, 1000);
this will wait 1 second for finish of __doPostBack() function.
Or if you don't want to use timeOut, paste window.location.href = abc; line to end of the __doPostBack() function.

call javascript method from codebehind

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.

Categories

Resources