Calling javascript from content page not working - javascript

My app consists of a Masterpage with content pages. The Masterpage contains javascript functions to manipulate a treeview by dynamically selecting and expanding nodes. In one instance I am trying to call the javascript function on the Masterpage through code-behind on a content page but the javascript never gets called. I placed break points in the javascript but they never get hit.
What needs to happen is that after the projects are deleted, the content page reloads and at the same time I need the javascript function to be called.
NOTE: the javascript does work as dynamically built links throughout the system do hit the breakpoints and the function runs.
Here is the code-behind method that I am making the call to the javascript from:
Protected Overrides Sub OnDelete(ByVal SelectedItems As System.Collections.Specialized.NameValueCollection)
For i As Integer = 0 To SelectedItems.AllKeys.GetLength(0) - 1
Dim strProjectId As String = SelectedItems.AllKeys(i)
Dim objProject As New BSProject(strProjectId)
BSProject.Delete(Val(strProjectId), Page)
' log action
BSActivity.Log(Page.User.SiteUser.intID, "Project Delete", _
"Project """ & objProject.strProjectName & """ of Organization """ & _
Projects.objOrganization.strName & """ was deleted")
Next
Dim script As ClientScriptManager = Page.ClientScript
script.RegisterStartupScript(GetType(Page), "RefreshProject", "parent.refreshNodeForProjects('" & Projects.objOrganization.intID.ToString() & ":company','" & Projects.objLocation.intID.ToString() & ":location" & "');") ' "parent.refreshNodeForProjects('" & Projects.objOrganization.intID.ToString() & ":company','" & Projects.objLocation.intID.ToString() & ":location" & "');", False)
If BSConfig.GetValue("ProjectsRefresh") = "1" Then
Response.Redirect(Request.RawUrl)
End If
End Sub
Here is the javascript function on the MasterPage:
function refreshNodeForProjects(company, location) {
try {
var tree = $find("<%= radprojecttree.ClientID %>");
if (company != '') {
rootnode = tree.findNodeByValue(company);
rootnode.set_expanded(false);
rootnode.get_treeView().trackChanges();
rootnode.get_nodes().clear();
rootnode.set_expandMode(2);
rootnode.get_treeView().commitChanges();
rootnode.set_selected(true);
rootnode.set_expanded(true);
if (location != '') {
rootnode = GetNodebyValue(rootnode, location);
rootnode.set_expanded(false);
rootnode.get_treeView().trackChanges();
rootnode.get_nodes().clear();
rootnode.set_expandMode(2);
rootnode.get_treeView().commitChanges();
rootnode.set_selected(true);
rootnode.set_expanded(true);
}
scrollToNode(tree, rootnode);
}
}
catch (ex) {
throw ex;
}
}

Created dynamic registered script block to handle this issue.

Related

Button not firing the third time - ASP.NET code behind C#

I have written a code for button click that should retrieve data from the database and display the data row wise as required. It is working Fine for the first two clicks and it is not firing for the third time... I really don't understand why Please any help.
thank you in advance
The button code
protected void NextButton_Click(object sender, EventArgs e)
{
c++; //integer created to iterate through rows of datatable
qno++; //just counts the rows begining from 1 and displays on page
SqlCommand lque = new SqlCommand("select * from questions where course='" + cour + "' and [group]='" + gr + "' and semester='" + sem + "'", con);
IDataReader rque = lque.ExecuteReader();
if (rque.Read())
{
DataTable dt = new DataTable();
dt.Load(rque);
QuestionNo.Text = Convert.ToString(qno);
Question.Text = dt.Rows[c].Field<string>(4);// only displaying the required columns.
RadioButton1.Text = dt.Rows[c].Field<string>(5);
RadioButton2.Text = dt.Rows[c].Field<string>(6);
RadioButton3.Text = dt.Rows[c].Field<string>(7);
RadioButton4.Text = dt.Rows[c].Field<string>(8);
}
}
source code for the button
<asp:Button ID="NextButton" runat="server" Text="Next" Width="111px" OnClick="NextButton_Click" />
i also checked the data is loaded without any errors into the datatable by passing the datatable as a source to the gridview, it shows all the rows in gridview but in the labels the first 2 rows only displaying. I also chekced the counting varible is only increasing 2 times.enter image description here
a few rows from the table that i am retrieving
Your variables(c for example) will be reset to 0 on every request(button-click). Http is stateless. So you need to persist this value somewhere else(i.e. Session, ViewState, Hiddenfield, etc).
For example with Session, which you should only use if this site has not too much traffic:
private int CurrentRowIndex
{
get
{
if (Session["CurrentRowIndex"] == null)
Session["CurrentRowIndex"] = 0;
return (int)Session["CurrentRowIndex"];
}
set => Session["CurrentRowIndex"] = value;
}
protected void NextButton_Click(object sender, EventArgs e)
{
int currentRowIndex = ++CurrentRowIndex;
// maybe you need this also for your other variables
// ...
}
You should also not read all rows if you only want one, you should modify your sql query. If you use MS SQL-Server you could use ROW_NUMBER function to select only the required row from DB.

Automate webpage which use JavaScript function

I want to automate this URL. My inputs as an example:
Input boxes:
افزودن صندوق with id="symbolSearch"
افزودن شاخص with id="indexSearch"
some values for symbolSearch:
I search کیان then I click on آوای ثروت کیان-در سهام
I search خوارزمی then I click on مشترك خوارزمي-در سهام
some values for indexSearch:
I search شاخص کل then I click on شاخص کل
I search شاخص کل then I click on شاخص كل (هم وزن)
How can I automate this in VBA ?
NOTE: Each element in "symbolSearch" associate with a mutual fund which has specific RegNo. The URL search elements within this link
Sub MakeChart()
Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")
'Get the WebPage Content to HTMLFile Object
With appIE
.navigate "http://www.fipiran.ir/AnalysisTools/MFInteractiveChart"
.Visible = True
'wait until the page loads
Do While .Busy Or .readyState <> READYSTATE_COMPLETE
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:05"))
For Each cell In Range("C:C")
If Not IsNumeric(cell) Or cell.Value = "" Or cell.EntireRow.Hidden Then GoTo Next_iteration
'''
**' codes to add RegNo in range C:C to webpage **
Next_iteration:
Next
.Quit
End With
Set appIE = Nothing
End Sub
I am not sure I have understood fully. I can parse the regNos from the first link using a JSON parser and store those in an array. I can then concantenate those numbers into an XMLHTTP request URL string that returns JSON data which I store in another array which you could parse.
Option Explicit
Public Sub GetInfo()
Dim url As String, json As Object, item As Object, regNos(), responseInfo(), i As Long
url = "http://www.fipiran.ir/AnalysisTools/MFAutocomplete?term="
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False
.send
Set json = JsonConverter.ParseJson(.responseText)
ReDim regNos(1 To json.Count)
ReDim responseInfo(1 To json.Count)
For Each item In json
i = i + 1
regNos(i) = item("RegNo")
Next
For i = LBound(regNos) To 2 'UBound(regNos)
.Open "GET", "http://www.fipiran.ir/AnalysisTools/MFHistory?regNo=" & CStr(regNos(i)), False
.send
responseInfo(i) = .responseText
'Application.Wait Now + TimeSerial(0, 0, 1) '< == to avoid being blocked
Next
End With
End Sub
Example info in responseInfo array:
After adding the jsonconverter.bas to the project I add a reference via VBE> Tools > References to Microsoft Scripting Runtime.

Opening a GridView Row in the same window as Parent Page while retaining my values?

I have this VB.NET code for a ASP.NET Gridview :
Protected Sub GridView3_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
e.Row.Cells(1).Attributes("onmouseout") = "this.style.textDecoration='none';"
Dim Index As Integer = e.Row.RowIndex
e.Row.Cells(1).Attributes("OnClick") = "window.open('AreaQuery.aspx?AreaID=" + GridView3.DataKeys(e.Row.RowIndex).Value.ToString + "');"
End If
End Sub
The Line of code :
e.Row.Cells(1).Attributes("OnClick") = "window.open('AreaQuery.aspx?AreaID=" + GridView3.DataKeys(e.Row.RowIndex).Value.ToString + "');"
Opens up the new page ( with the passed values ) in a new window , I need this to be in the same window as the page it's come from ... How do I achieve this & How would it be implemented?
try to use this '_self'
<script type="text/javascript">
window.open ('YourNewPage.htm','_self',false)
</script>
http://www.w3schools.com/jsref/met_win_open.asp

need jQuery confirmation message emitted during asp.net postback logic

I have a "registration" type webform in ASP.Net. When the user clicks the submit button, Page.IsPostBack code updates a database and "informs user" that redirection to Login page will occur. This all works OK but is quite ugly and I would like to make it more "elegant". Here is a snippet of my current technique clipped from Page_Load (IsPostBack):
Dim wrapper As New StringBuilder
Dim inner As New StringBuilder
inner.Append("Company ID ") 'txtCompanyID
inner.Append(Convert.ToString(Me.txtCompanyID.Text))
inner.Append(" has been successfully created. ")
inner.Append("\nYou will now be redirected so you can Login for the first time.")
wrapper.Append("<script language='javascript'>")
wrapper.Append("window.alert('")
wrapper.Append(inner.ToString()) 'inject real message into wrapper
wrapper.Append("');")
wrapper.Append("window.location.href='")
wrapper.Append("../Login.aspx';")
wrapper.Append("</script>")
Response.Write(wrapper.ToString())
I have a little experience using jQuery UI dialog as a more styled alternative to Javascript - but these dialogs get invoked from client-side click events and I can't see how to inject jQuery into the above approach (I suspect there must be a better technique but I just can't find it yet).
Ideally, I'd want a nicely styled confirmation message where clicking an OK button takes the user to the specified new page.
#gbs - thanks for the suggestion. From that and some more research and testing I came up with a solution I'll try to summarize here for future poor rookies like me:
First, the IsPostBack logic in the .aspx reduces down to constructing a message which will be the main inner content of the jQuery UI dialog and passing it to new common sub. So, the code in the OP is as follows:
Dim inner As New StringBuilder
inner.Append("Success! Your account has been created.<br/><br/>")
inner.Append("A confirmation email message has been sent to you.<br/><br/>")
inner.Append("Just click OK and you will be redirected to <b>Login</b> for the first time.")
UIF.MsgBoxJQUI(inner.ToString(), "TCB Welcomes You", "OK", "../Login.aspx")
Next, in a common classes library project referenced by the UI, I added this:
Public Class UIFunction
Public Shared Sub MsgBoxJQUI(ByVal htmlMsg As String, _
Optional ByVal title As String = "Please note:", _
Optional ByVal caption As String = "OK", _
Optional ByVal newURL As String = Nothing)
Dim currentPage As System.Web.UI.Page = TryCast(HttpContext.Current.Handler, UI.Page)
If currentPage IsNot Nothing Then ' use page instance..
currentPage.ClientScript.RegisterStartupScript(currentPage.Page.[GetType](), _
"dialog", _
jQueryUIalert(htmlMsg, title, caption, newURL), _
True)
End If
End Sub
Private Shared Function jQueryUIalert(ByVal innerMsg As String, _
Optional ByVal title As String = "Please note:", _
Optional ByVal caption As String = "OK", _
Optional ByVal newURL As String = Nothing) As String
Dim wrapper As New StringBuilder
wrapper.Append("$(function(){showDialog3('")
wrapper.Append(innerMsg) 'inject real message into wrapper
wrapper.Append("','")
wrapper.Append(title)
wrapper.Append("','")
wrapper.Append(caption)
wrapper.Append("','")
wrapper.Append(newURL)
wrapper.Append("')")
wrapper.Append("});")
Return wrapper.ToString()
End Function
Next, I added the following reference in the head of my SiteLayout.master page:
<script type="text/javascript" src="<%= ResolveClientUrl("~/js/sitewide.js") %>"></script>
Next, the actual Javascript function in the sitewide.js file invokes jQuery as follows:
//The following function is called from the script injected from code-behind.
function showDialog3(message, title, caption, nextUrl) {
title = title || 'Welcome to TCB';
caption = caption || 'OK';
nextUrl = nextUrl || '../Login.aspx';
$('body').append("<div id='some-Message'></div>");
$("#some-Message").dialog({
autoOpen: false,
dialogClass: 'myAlert',
buttons: [
{
text: caption,
click: function() {
$(this).dialog("close");
}
}
],
create: function() {
$(this).closest(".ui-dialog").find(".ui-button").eq(1).addClass("deleteButtonClass");
},
hide: 'blind',
height: 'auto',
width: 'auto',
close: function(event, ui) { window.location.href = nextUrl; },
modal: true,
show: 'blind',
title: title
}).dialog('widget')
.next(".ui-widget-overlay")
.css("background", "#737373");
$("#some-Message").append(message);
$("#some-Message").dialog('open');
$('.ui-widget-overlay').css('background', '#737373');
}

How to get client id for grid view from inside a view to use in javascript

I have a grid view that I want to use with JavaScript to calculate values entered in the textboxes.
I was adding onkeyup to the textboxes in the onrowcreated function and it was working fine.
Then I put the gridview in a multiview, and it stopped working.
This is my JavaScript function:
function margin1(rowIndex, price, gridId) {
var grid = document.getElementById(gridId);
var volumeQuota = grid.rows[rowIndex].cells[2].innerText;
alert(volumeQuota);
var coef = grid.rows[rowIndex].cells[5].childNodes.item(1).value;
alert(coef);
var prevSites = grid.rows[rowIndex].cells[4].innerText;;
grid.rows[rowIndex].cells[6].childNodes.item(1).value = parseFloat(coef) * (parseFloat(volumeQuota) - parseFloat(prevSites));
grid.rows[rowIndex].cells[7].childNodes.item(1).value = price;
}
and in the code behind this is how im adding it.
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t1 = (TextBox)e.Row.FindControl("p98Margin1");
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', {1}, {2})", e.Row.RowIndex + 2, a98.Text , GridView1.ClientID));
when I alert Gridview1.clientId in the JavaScript function I'm getting [objectHTMLTableElement]
use this
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', '{1}', '{2})'", e.Row.RowIndex + 2, a98.Text , GridView1.ClientID));
I think this should work.
I think the value should go in single quotes ' mark.
Like you said you put your grid in a multiview and everything stopped working,which means your gridview has been buried and you need to drill down a bit further to expose it.
Do this
GridView myGridView=(GridView)(MultiView1.FindControl("GridView1"));
Now you have located it gracefully reference its ID
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t1 = (TextBox)e.Row.FindControl("p98Margin1");
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', {1}, {2})", e.Row.RowIndex + 2, a98.Text ,myGridView.ClientID));
}
Hope this helps.

Categories

Resources