need jQuery confirmation message emitted during asp.net postback logic - javascript

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');
}

Related

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.

Show image after button click

I have a controller method that returns image in byte array, from MongoDB, and I want to show it in my view:
<HttpPost()>
Function ShowImage(id As String) As FileContentResult
Dim Handler = New MongoDBHandler()
Dim newString = id.Replace(vbLf, "").Trim().Replace("""", String.Empty)
Dim byteArray = Handler.ReadImage(newString)
Return File(byteArray, "image/png")
End Function
I have the javascript function:
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "/MyController/MyMethod/CardNumber");
$("#myModal").append($img);
}
The Table:
When the "Show" button click, on the table, the "No." cell (and is data) is sent to the JS function, and pass to the controller, then i try to create new image element with, and add it to my popup modal for show.
The problem is i cant get the controller response, and spent hours in google search for it, any solutions please?
try following and check if it work. Please verify that the controller name you are specifying in following URL is correct.
I am not sure that your controller name is "MyController". check it and change if it is wrong.
If following code doesn't work, send me the url it generated in comment
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "#(Url.Action("ShowImage","CreditCard"))/" + CardNumber);
$("#myModal").append($img);
}

Calling javascript from content page not working

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.

How to fire postback in a specific jQuery UI tab in an ASP.NET webform

I have some jQuery UI tabs in ASP.NET web form. Everything works OK, but by default the first tab is opening.
I am executing some code in a modal popup and when the user clicks the action button, I want the postback to be in the tab from which the popup was triggered.
This is the jQuery UI tabs code:
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
I want to know how can I select which tab to be opened by default when page is loaded, for example if I have in the query string:
mypage.aspx?tab=1 or mypage.aspx?tab=2
Some other example might work better.
Use the getParameterByName function from this question to get the value:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then do something like this:
$("#tabs").tabs({
create: function(event, ui){
var index = parseInt(getParameterByName("tab"));
$(this).tabs("option", "active", index);
}
});
Links:
http://api.jqueryui.com/tabs/#option-active
It sounds like you want the two things I wanted when I worked through this problem yesterday: (1) ability to specify a starting tab, and (2) control of which tab opens after a postback from the page. One approach: include a hidden field in your .aspx:
<asp:HiddenField runat="server" ID="hfLastTab" Value="0" />
(assuming the first/0th tab is your default if nothing's specified). In Page_Load(), provide a !Page.IsPostBack branch to parse a querystring parameter, and set the hidden field's value:
if (!Page.IsPostBack) {
string pat = #"t=(\d)";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(Request.Url.Query);
if (m.Success) hfLastTab.Value = m.Groups[0].ToString();
}
Finally, the jQuery ready function tells which tab to show, based on the hiddenfield's value:
$(function () {
$("#tabs").tabs({ active: <%= hfLastTab.Value %> });
});
The server-side postback handling code likewise can set hfLastTab.Value to the appropriate index. If your modal popup can be raised by more than one tab, and you don't know by the control which tab you want to open, you'll have to do a bit more work. From an answer to a similar question, specifying an 'activate' function in the jQuery will set the hiddenField value when the user selects a tab, which you could read from the postback:
$("#tabs").tabs({
activate: function() {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#<%= hfLastTab.ClientID %>").val(selectedTab);
},
active: <%= hfLastTab.Value %>
});

Javascript code to get ProductID?

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?

Categories

Resources