I have a two JavaScript message boxs in an if statement which arent firing - the compiler just bypasses the code as if its not there. This exact same code works elsewhere when its outside the if statement. Can anyone shed some light as to why this isnt working? Thanks
If chk1.Checked And chk4.Checked Then
Dim message As String = "Invalid"
Dim sb As 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(Me.GetType(), "alert", sb.ToString())
Else
If chk2.Checked = True And chk5.Checked = True Then
Dim message2 As String = "Invalid"
Dim sb2 As New System.Text.StringBuilder()
sb2.Append("<script type = 'text/javascript'>")
sb2.Append("window.onload=function(){")
sb2.Append("alert('")
sb2.Append(message2)
sb2.Append("')};")
sb2.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb2.ToString())
Else
Try replacing:
sb2.Append("</script>")
With:
sb2.Append("<\/script>")
in both conditions.
Browser does not allow direct injection, you need to trick it.
I wonder why you are mixing Javascript and VBScript together or how it is gonna run.
Make sure that your onload event isn't setting the checkboxes. The ASP.net lifecycle specifies that the onload event will fire first and therefore set the checkboxes to what is defined in the onload section. If you need to avoid this, just wrap the code that sets the checkboxes in a
if not isPostback then statement to avoid this from happening
aspx:
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<asp:CheckBox ID="CheckBox1" Text="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="CheckBox2" runat="server" />
vb:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim message As String = "not (chk1 and chk2)"
If CheckBox1.Checked And CheckBox2.Checked Then
message = "chk1 and chk2"
Else
If CheckBox1.Checked Then
message = "chk1"
ElseIf CheckBox2.Checked Then
message = "chk2"
End If
End If
Dim sb As 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(Me.GetType(), "alert", sb.ToString())
End Sub
i tested this code ....
try == rather than = in if condition!
Related
Good day,
I have a repeater that contain link button. The value and number of link button is generate base on data pull from database. The HTML code is something as follow:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
Here is some code that I try to do in my code behind,
for (int i = 0; i < table.Rows.Count; i++)
{
RepeaterItem itm = repCategories.Items[i];
GiftRow dr = tbl.GetRow(i);
Literal litLink2 = (Literal)itm.FindControl("litLink2");
litLink2.Text = dr.Name;
string myScript = string.Empty;
myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
}
By doing this, I will get alert hi when I load the page.What I want to do is, I only want it do alert hi when I click on the link button, instead of page load.
Use a LinkButton and leverage the ClientClick event instead:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
<asp:LinkButton ID="lbMyLinkButton" runat="server" />
</ItemTemplate>
</asp:Repeater>
I'd also recommend you use ItemDataBound events of repeaters where possible:
void repCategories_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((LinkButton)e.Item.FindControl("lbMyLinkButton")).OnClientClick = "alert('hi');";
}
}
NOTES:
I wouldn't ever recommend you render javascript server-side unless absolutely necessary. I've provided an answer to fit in with the context of your question, but I would advise you have a javascript function already on your page and 'wire it up' server-side (if not bind it on the client with pure javascript)
There is also an assumption here that you're binding data to the repeater (you should be anyway), which means you also have to wire up the ItemDataBound handler: repCategories.OnItemDataBound += repCategories_ItemDataBound
within a gridview, i have a template column, which has a linkButtton column within it.
when the linkButton column is clicked, it triggers the client side, which if TRUE should call the server side event.
but somehow, the server side event is been invoked in both cases - TRUE or FALSE.
please let me know, if i'm missing on something......
markup code goes as --
<asp:TemplateField HeaderText="Disable/Enable" ItemStyle-Width="10%" HeaderStyle-HorizontalAlign="Left"#
<ItemTemplate>
<asp:LinkButton runat="server" ID="ableDisableLaborCode" CommandName="linkButtonClick" CommandArgument='#%# Eval("coLaborCodeID") %#'##/asp:LinkButton#
</ItemTemplate>
</asp:TemplateField>
This is where the client side event is registered
Private Sub gridVwCoLaborCodes_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridVwCoLaborCodes.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim _lnk As LinkButton = DirectCast(e.Row.FindControl("ableDisableLaborCode"), LinkButton)
Dim _drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
_lnk.Text = If(CBoolBit(_drv(Fields.NAME_FIELD_IS_ENABLED_FLAG)), "Disable", "Enable")
_lnk.OnClientClick = String.Format("return confirm('Are you sure you want to deactivate this labor code ?');")
End If
End Sub
following is the code for the server side event --
Private Sub gridVwCoLaborCodes_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridVwCoLaborCodes.RowCommand
If e.CommandName = "linkButtonClick" Then
CoLaborCodeId = CIntNull(e.CommandArgument.ToString())
End If
End Sub
thanks to all viewed and helped.
Try to assign the javascript event in a different way:
Private Sub gridVwCoLaborCodes_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridVwCoLaborCodes.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim _lnk As LinkButton = DirectCast(e.Row.FindControl("ableDisableLaborCode"), LinkButton)
Dim _drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
_lnk.Attributes.Add("onclick", "return confirm('Are you sure you want to deactivate this labor code ?');")
lnk.Text = If(CBoolBit(_drv(Fields.NAME_FIELD_IS_ENABLED_FLAG)), "Disable", "Enable")
End If
End Sub
I tried
Protected Sub btn_add_question_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add_question.Click
frm_course.Visible = False
question_div.Visible = True
ScriptManager.RegisterClientScriptBlock(btn_add_question, Me.GetType(), "BlockName", "alert('hello world');", True)
End Sub
and
Protected Sub btn_add_question_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add_question.Click
frm_course.Visible = False
question_div.Visible = True
Page.ClientScript.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello')")
End Sub
But, alert message is not showing. Need Help !!
<asp:Button ID="btn_add_question" runat="server" Text="Next" CssClass="btn_submit" Width="101px" />
You need to add the <script> tags to the function call by passing True as the last parameter to RegisterStartupScript as so:
Page.ClientScript.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello');",True)
UPDATE:
Try this:
ScriptManager.RegisterStartupScript(Me.GetType, "Javascript", "alert('hello');",True)
add an OnClientClick handler to the button or, better yet, attach the handler through javascript where it should be.
<asp:button id="myButton" runat="server" text="Postback" onclientclick="alert('hello world');" />
if all you are doing is changing some visibility of some elements, you shouldn't even be doing a post back at all. just use an input type="button" and show/hide through javascript.
<input type="button" value="Next" id="btn_add_question" />
document.getElementById('btn_add_question').onclick = function () {
document.getElementById('frm_course').style.visibility = 'hidden';
document.getElementById('question_div').style.visibility = 'visible';
alert('hello world');
};
I have a webservice that gets a ProductName and I need the Products that are dropped down from the AutoExtender to be links to each product's individual page.
Right now the URL gets filled with the ProductName, and not the ID:
Default.aspx?id=Test%20Product
needs to be
Default.aspx?id=519
*Note - this site is for internal use only, so we are not worried about getting hacked right now. We want the site to work.
I have been told that what I want to do is not possible by people on the forum for asp.net so I came here hoping for some help. I think it is the javascript that is getting the ProductName from the webservice, and I need it to get the ProductID. I tried rewriting the For Each loop to include ProductID instead of ProductName, but then the AutoCompleteExtender only shows IDs in the results instead of the ProductNames.
Javascript:
<script type="text/javascript">
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_value();
window.location = ("/Product/Default.aspx?id=" + value)
}
</script>
Here is the code for my autoCompleteExtender and the webservice:
<asp:TextBox ID="Search" runat="server" AutoComplete="off"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetProducts" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" OnClientItemSelected="AutoCompleteClientMethod">
</asp:AutoCompleteExtender>
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class ProductSearch
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetProducts(ByVal prefixText As String, ByVal count As Integer) As String()
Dim ProductSql As String = "Select DISTINCT ProductID, ProductName FROM Product WHERE ProductName LIKE '%" & prefixText & "%' ORDER BY ProductName ASC"
Dim sqlConn As New SqlConnection
sqlConn.Open()
Dim myCommand As New SqlCommand(ProductSql, sqlConn)
Dim myReader As SqlDataReader = myCommand.ExecuteReader()
Dim myTable As New DataTable
myTable.TableName = "ProductSearch"
myTable.Load(myReader)
sqlConn.Close()
Dim items As String() = New String(myTable.Rows.Count - 1) {}
Dim i As Integer = 0
For Each dr As DataRow In myTable.Rows
items.SetValue(dr("ProductName").ToString(), i)
i += 1
Next
Return items
End Function
End Class
Edit: Adding the way the search results used to show up before the switch to the AutoCompleteExtender. I have tried to incorporate this into what I have now, but I can't get anything to work right. Please note that this is the OLD code, what is above is all the code I am using NOW.
<div class="hiddenResults">
<ul id="hiddenResults" style="display:none;">
<asp:ListView ID="lvProducts" runat="server" DataSourceID="dsProducts">
<ItemTemplate>
<li><span class="title"><%# eval("ProductName") %></span></li>
</ItemTemplate>
</asp:ListView>
</ul>
</div>
I tried
<ul style="list-style:none;"><li><a href='/Product/Default.aspx?id=<%# eval("ProductID") %>'>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="Search" ServicePath="~/ProductSearch.asmx" ServiceMethod="GetProducts" MinimumPrefixLength="1" CompletionSetCount="120" EnableCaching="true" OnClientItemSelected="AutoCompleteClientMethod">
</asp:AutoCompleteExtender></a></li></ul>
but having the autocomplete extender in a list keeps the results of the query from showing.
Edit: Working code:
For Each dr As DataRow In myTable.Rows
Dim id As String = dr("ProductID").ToString()
Dim name As String = dr("ProductName").ToString()
Dim item As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(name, id)
items.SetValue(item, i)
i += 1
Next
See this article, or this one.
In short, create your list items using CreateAutoCompleteItem(). Modify the loop in GetProducts to use CreateAutoCompleteItem():
For Each dr As DataRow In myTable.Rows
dim id as String = dr("ProductId").ToString()
dim name as String = dr("ProductName").ToString()
dim item as String = AutoCompleteExtender.CreateAutoCompleteItem(name, id)
items.SetValue(item, i)
i += 1
Next
That sends both the name and the id to the client. That step is crucial. (If there are syntax errors above, forgive me... It's been a long time since I coded much VB - mostly C# these days.)
Then modify your OnClientItemSelected handler to use get_key() instead of get_value() for the url:
function AutoCompleteClientMethod(source, eventArgs) {
var value = eventArgs.get_key();
window.location = ("/Product/Default.aspx?id=" + value)
}
You need to wrap the href in single quotes, like this:
<a href='/Product/Default.aspx?id=<%# eval("ProductID") %>'>
Now, what are you trying to do with the autocomplete extender? Are you trying to load the results with JavaScript?
I am using a asp.net listbox. I have two buttons one to add items to listbox and another to remove. I am using javascript function to remove items from the listbox. When I add to the listbox after removing. The removed items are also getting added.
<asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox>
<asp:LinkButton ID="sLbtnAdd" runat="server" ></asp:LinkButton>
Remove
function fncRemoveItems()
{
var i;
var strIDs="";
var items = document.getElementById("sLstbox");
alert(items.options.length);
for (i = items.options.length - 1; i >= 0; i--)
{
if (items.options[i].selected)
items.remove(i);
}
}
IN code
Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
Dim li As New ListItem
li.Value = "1"
li.Text = "test"
sLstbox.Items.Add(li)
End Sub
You should be using normal < select > boxes in this case.
asp:listboxes are meant to be manipulated at server side and you need to hack around that to make it work the way you want.
With normal select-boxes (either runat server or not) it should be pretty straight forward.
If you want to make your life a lot easier and give you the 'AJAX' effect, just put it all in an UpdatePanel and do it server side. If you want to use an asp:ListBox, manipulating it via javascript is going to a pain.
Here is a working example with the aspx code and the codebehind implementation for your scenario:
<asp:UpdatePanel ID="yourUpdatePanel" runat="server">
<ContentTemplate>
<asp:ListBox ID="sLstbox" runat="server" Width="250px" Height="150px" TabIndex="10"></asp:ListBox>
<asp:LinkButton ID="sLbtnAdd" runat="server" OnClick="sLbtnAdd_Click" ></asp:LinkButton>
<asp:LinkButton ID="sLbtnRemove" runat="server" OnClick="sLbtnRemove_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
In your codebehind:
Protected Sub sLbtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
Dim li As New ListItem
li.Value = "1"
li.Text = "test"
sLstbox.Items.Add(li)
End Sub
Protected Sub sLbtnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sLbtnAdd.Click
For i As Integer = sLstbox.Items.Count - 1 To 0 Step -1
If sLstbox.Items(i).Selected Then
sLstbox.Items.Remove(sLstbox.Items(i))
End If
Next
End Sub