Toastr Alert Asp.Net Vb - asp.net

Im trying to do some alert messages on a web form in visual studio vb, but it keeps giving me this error when i try and code it dynamically in the action method
"only content controls are allowed directly in a content page that contains content controls"
i have left the old code in where it just produces a label error message into the HTML
getting a blue wave line underneath this line
popupScript = "<script language='javascript'>" + "showErrorToast();" + "</script>"
jquery function
<script type="text/javascript">
function showErrorToastr() {
toastr.warning('Please enter at least 3 characters of the organisation name')
}
Vb Action method when cancel button its clicked
Protected Sub btnSelect0_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim popupScript As String = ""
If txtorgname.Text = "" Then
lblerror.Text = "Please enter at least 3 characters of the organisation name"
txtorgname.Focus()
popupScript = "<script language='javascript'>" + "showErrorToast();" + "</script>"
ElseIf Len(txtorgname.Text) < 3 Then
lblerror.Text = "Please enter at least 3 characters of the organisation name"
txtorgname.Focus()
ElseIf Len(txtorgname.Text) > 50 Then
lblerror.Text = "Organisation name too long. Max 50"
txtorgname.Focus()
Else
BindData()
End If
End Sub

showErrorToast does not exist in your example, but showErrorToastr does.
Try that change. If it doesn't work, please comment.

Related

How to insert a gridview with a row image button into the email body

I wrote some code that sends emails and inserts a table cell from Gridview.
Protected Sub SendRequestMail()
Dim tryCount As Integer = 5
Dim failed As Boolean = False
Do
Try
failed = False
Dim ToMailIDs As String
ToMailIDs = LblRecipients.Text
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Dim mm As MailMessage = New MailMessage()
mm.From = New MailAddress(smtpSection.From, "Notification")
For i As Integer = 0 To ToMailIDs.Split(","c).Length - 1
mm.To.Add(New MailAddress(ToMailIDs.Split(","c)(i)))
Next
mm.ReplyTo = New MailAddress("xxxxx#xxxxx.xxx")
mm.Subject = LblMrNumFull.Text & " | " & LblMrDate1x.Text & " | " & LblStorsName1.Text & " - Approval"
mm.Body = LblMrNumFull.Text & " | " & LblMrDate1x.Text & " | " & LblStorsName1.Text
mm.Body += sw.ToString()
mm.Body += "<br />"
mm.Body += "Thanking you"
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.Delay
mm.Headers.Add("Disposition-Notification-To", "yyyyyy#xxxxx.xxx")
' ----- webconfig mail start
mm.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
smtp.Send(mm)
' ----- webconfig mail end
End Using
End Using
Catch ex As Exception
failed = True
tryCount = tryCount - 1
Finally
Response.Redirect("~/abc/xyx.aspx?NewID=" & Request.QueryString("NewID"))
End Try
Loop While failed AndAlso tryCount > 0
End Sub
That code worked, and the email was successfully sent.
After that, I have added an image button to the last column in the Gridview:
Then emails stop being sent. Please suggest the above code for sending emails with or without the last column of image buttons.
tried nothing works
'To Export all pages.
GridView1.AllowPaging = False
Me.BindData_GridView1()
GridView1.HeaderRow.BackColor = Color.White
For Each cell As TableCell In GridView1.HeaderRow.Cells
cell.BackColor = GridView1.HeaderStyle.BackColor
Next
For Each row As GridViewRow In GridView1.Rows
row.BackColor = Color.White
For Each cell As TableCell In row.Cells
If row.RowIndex Mod 2 = 0 Then
cell.BackColor = GridView1.AlternatingRowStyle.BackColor
Else
cell.BackColor = GridView1.RowStyle.BackColor
End If
cell.CssClass = "textmode"
Next
Next
Are the images provided by a URL?
You could consider converting the image to a in-line "base64" string, and thus the html rendering for the GV would not include links.
It is possible (but not yet determined) that you don't want images as "links" to a url that is of course pointing to your site.
In other words, if you attempting to add/render/inject/have/use/enjoy some images in the the html for that body, try using "strings" and not an actual URL to the image.
So, say this example simple gv
<h3>Hotels</h3>
<asp:GridView ID="GridView1" runat="server" Width="40%"
AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table table-striped">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="cmdApprove" runat="server"
ImageUrl="~/Content/Pictures/check1.jpg"
Width="48"
OnClick="cmdApprove_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
GridView1.DataSource = Myrst("SELECT * FROM tblHotelsA ORDER BY Hotelname")
GridView1.DataBind()
End Sub
And we now have this:
but, now lets hit f12 for browser dev tools, and elements, and inspect that ImageButton, and we find/get this:
<input type="image" name="GridView1$ctl03$cmdApprove"
id="GridView1_cmdApprove_1"
src="../Content/Pictures/check1.jpg"
style="width:48px;">
Well, I can't see HOW that grid view going to THEN render in a email body, since you have path names and "urls" to your web site, and worse yet, they are relative path names that will ONLY work to the current given web site, and ONLY work on the CURRENT folder page
Note the "../" for the path name! If you moved that web page to a different folder, NOT EVEN that simple path name would work anymore!!!
So, lets remove the URL from that ImageButton.
And lets "stream" + inject the picture as a imbedded byte array.
So, our image button now becomes this:
<ItemTemplate>
<asp:ImageButton ID="cmdApprove" runat="server"
Width="48"
OnClick="cmdApprove_Click" />
</ItemTemplate>
So, no image.
but, now, in the row data bound event, we do this:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ImageBtn As ImageButton = e.Row.FindControl("cmdApprove")
ImageBtn.ImageUrl = gImageBytes("~/Content/Pictures/check1.jpg")
End If
End Sub
Function gImageBytes(sFile As String) As String
Dim sFileInternal As String =
Server.MapPath(sFile)
Dim iBytes As Byte() = File.ReadAllBytes(sFileInternal)
Dim sMineType As String = MimeMapping.GetMimeMapping(sFileInternal)
Return $"data:{sMineType};base64,{Convert.ToBase64String(iBytes, 0, iBytes.Length)}"
End Function
When we run, the gv looks the same.
but, now inspecting the markup, we get/see this:
<input type="image" name="GridView1$ctl02$cmdApprove"
id="GridView1_cmdApprove_0"
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAS etc."
style="width:48px;">
I "cut" the rest of the bytes for the image, but note now, how the markup does NOT have a URL path name to some image on the web server - of which the client side email body will never have.
So, the above would/could/will remove the path name to a image in that grid.
However, even better?
I would "hide" the buttons (visible = false) means that the html is NOT rendered in the gv, and thus you wind up removing the buttons 100%. So in row databound, hide the button(s) - their markup will NOT be rendered.
So, say like this:
At page class, define a flag, say like this:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ImageBtn As ImageButton = e.Row.FindControl("cmdApprove")
ImageBtn.Visible = Not (bHideGridButtons)
ImageBtn.ImageUrl = gImageBytes("~/Content/Pictures/check1.jpg")
End If
End Sub
So, now gv becomes this:
Or, another idea? , and either create a 2nd gv, and use that for the email.
(I can't see the point to include the buttons in some email body anyway!).
So, you could try removing the images.
However, before one does ANY of that?
Create a seperate 100% routine say like this:
Call SendMailWeb(strTO, strSubject,
strBody, True, strCC, strBC,
FileAttachments, strReplyFromList)
or "whatever".
So, with a seperate routine to call, then this will allow easy coding, but ALSO allow you to make some test grids based on above ideas, such as removing the image link, and using "streaming"
I VERY often for even display of images, or even for users to download a file?
I don't allow, proivde, use, have any public or file based "URL" path names allowed from the web site and markup. all file operations are 100% from code behind, and thus I never expose files at any time to allowable public URL's from the web site. (this is done for security reasons, and also to say have users download a PDF document, but that folder of pdf's is not exposed as any URL public path name.
Code behind 100% ignores IIS security settings, and file path names are 100% plane jane server paths (good old fashioned windows path names). So, while this was a simple "image" example, it does show that URL's to some images does NOT have to be a valid and existing URL for that image to display, but only code behind reading a file as bytes, and then steaming out the image as a base 64 image string.
so, for darn near ANY image(s) in a email body, links and path names to pictures are NOT going to work in a email body on some client computer that may well not even have your web site URL's to picture path names available at all.
I got the solution from another forum, so I posted it below.
HTML
<%# Page Title="" Language="vb" AutoEventWireup="false" EnableEventValidation="false" MasterPageFile="~/abc/xyz.Master" CodeBehind="aaaa1.aspx.vb" Inherits="aaaa.sss" %>
VB.NET
Protected Sub SendRequestMail()
Dim tryCount As Integer = 5
Dim failed As Boolean = False
Do
Try
failed = False
Dim ToMailIDs As String
ToMailIDs = LblRecipients.Text
GridView1.Columns(GridView1.Columns.Count - 1).Visible = False
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim smtpSection As Net.Configuration.SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Dim mm As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage()
mm.From = New MailAddress(smtpSection.From, "Notification")
For i As Integer = 0 To ToMailIDs.Split(","c).Length - 1
mm.To.Add(New MailAddress(ToMailIDs.Split(","c)(i)))
Next
mm.ReplyTo = New MailAddress("xxxxx#xxxxx.xxx")
mm.Subject = LblMrNumFull.Text & " | " & LblMrDate1x.Text & " | " & LblStorsName1.Text & " - Approval"
mm.Body = LblMrNumFull.Text & " | " & LblMrDate1x.Text & " | " & LblStorsName1.Text
mm.Body += sw.ToString()
mm.Body += "<br />"
mm.Body += "Thanking you"
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.Delay
mm.Headers.Add("Disposition-Notification-To", "yyyyyy#xxxxx.xxx")
' ----- webconfig mail start
mm.IsBodyHtml = True
Dim smtp As SmtpClient = New SmtpClient
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
smtp.Send(mm)
' ----- webconfig mail end
End Using
End Using
GridView1.Columns(GridView1.Columns.Count - 1).Visible = True
Catch ex As Exception
failed = True
tryCount = tryCount - 1
Finally
Response.Redirect("~/abc/xyx.aspx?NewID=" & Request.QueryString("NewID"))
End Try
Loop While failed AndAlso tryCount > 0
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control) End Sub
Thank you

catch an event from a message box in asp.net

So my boss gaved me the project of adapting a vb.net aplication into asp.net but i never worked with asp.net before and im learning from the internet so dont blame me xD. So in my page after the login i wanted a msgbox to pop up saying "welcome" or something like that, and i managed to come across this code
MessageBox("Welcome to wrox forum")
Private Sub MessageBox(ByVal msg As String)
Dim lbl As New Label
lbl.Text = "<script language='javascript'>" & Environment.NewLine & _
"window.alert('" + msg + "')</script>"
Page.Controls.Add(lbl)
End Sub
so this works fine but after the message (after the user press the ok button) i would like to redirect the user to other page but i dont know how to create the event wich will trigger after the user press "ok" any ideas?
thank you,
The code after alert will execute once the dialog is closed. So just add your code at the end of the script, e.g.,
lbl.Text = "<script language='javascript'>" & Environment.NewLine & _
"window.alert('" + msg + "');" & Environment.NewLine & _
"document.location = 'https://www.GoHere.com';</script>"

aspnet/vbnet clear label after response redirect

I'm building an asp.net web page with vb.net code behind.
My web page is designed to display an error when the user clicks a button without filling the relevant textbox; the code below shows how this works:
If txtOrderNumber.Text = "" Then
lblStatus.Text = orderNoWarning
lblStatus.CssClass = "error"
ElseIf txtPhaseNumber.Text = "" Then
lblStatus.Text = phaseNoWarning
lblStatus.CssClass = "error"
ElseIf txtOrderNumber.Text.Length > 0 AndAlso txtPhaseNumber.Text.Length > 0 Then
Try
Dim intOrderNumber As Integer = CInt(txtOrderNumber.Text)
Try
Dim intPhaseNumber As Integer = CInt(txtPhaseNumber.Text)
Dim objWIP_Tracking As New wsWIP_Tracking.WIP_TrackingSoapClient
Dim myResults As wsWIP_Tracking.TicketType2 = objWIP_Tracking.GetTicketType2(intOrderNumber, intPhaseNumber)
If myResults = wsWIP_Tracking.TicketType2.AME Or _
myResults = wsWIP_Tracking.TicketType2.Orion Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummarybyComponent.rpt&username=imservices&FOLDER=Analytics&OrderNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = ""
Response.Redirect("http://ligrptsvr2/default.aspx?Report=JoinerySummary_GreenScreen.rpt&username=wip&FOLDER=Analytics&JobNo=" & intOrderNumber.ToString & "&PhaseNo=" & intPhaseNumber.ToString & "&ParameterPrompt=yes")
ElseIf myResults <> wsWIP_Tracking.TicketType2.AME Or _
myResults <> wsWIP_Tracking.TicketType2.Orion Or _
myResults = wsWIP_Tracking.TicketType2.GS Then
lblStatus.Text = warning
lblStatus.CssClass = "warning"
Else
Response.End()
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
Else
lblStatus.Text = ""
End If
However, when a response.redirect (redirects to new page) occurs , I would like to clear the label(lblstatus). The code 'lblstatus.text=""' does not work. When the user gets redirected to a new page then goes back (using browser back button), the label still shows an error. Iv tried disabling and enabling viewstate; doesn't make any difference. What can I do to clear this label?
Please see: What happens when I press browser BACK button?
When you press back button in a browser, most browsers will just display the cached copy of the html page in it's latest state, before the redirect happened. The functionality is totally browser dependent. Hence, your VB code or viewstate can hardly do anything.
One option is to use java-script on page load, to dynamically toggle the error message (which is what I do when I have this kind of a problem).

Clear Textboxes

Morning All,
I would like to have a cancel button on my web page that essentially i would like to clear form field and themn redirect users to the home page.
I have 7 txt boxes that i will need to clear before the page redirects. I have done some searching on the internets and have tried to put the following sample into my page with no luck....
With this code i get an error on the X = "" line. I get a message 'Value of type string cannt be converted to system.we.UI.control'
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
x = " "
End If
Next
End Sub
And i have also tried the below which also produces a Compilation Error.
For Each c As Control In Me.Controls
If TypeOf c Is TextBox Then
DirectCast(c, TextBox).Text = ""
End If
Next
Can anyone help me with resolving this issue?
Regards
Betty
Try this:
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
Dim txt as TextBox = x
txt.Text = ""
End If
Next
Explanation:
You tried to set a string to a Control-variable and of course the compiler does not know how to to this.
The version I gave will set the Text-property of each TextBox to the empty-String
You can use html code to reset all field of current form you are working with
use follwoing code to reset all fields
<input type="reset" value="Clear" onclick="redirectFunction()" />
and in redirectFunction write following javascript code:
function redirectFunction()
{
window.location="destination.aspx";
}
using above code you can redirect to destination page.

ASP CascadingDropDown Control Causes IE Script timeout

Before a page is loaded, I use a subroutine to link DropDownList controls together:
Private Sub CreateCascadingDropDown(ByVal category As String, ByRef parentDDL As DropDownList, ByRef targetDDL As DropDownList)
Dim CDDL As New CascadingDropDown
With CDDL
.Category = category
If Not parentDDL Is Nothing Then
parentDDL.Items.Clear()
.ParentControlID = parentDDL.ID
End If
targetDDL.Items.Clear()
.TargetControlID = targetDDL.ID
.PromptText = SharedWeb.GC_SELECTONE
.PromptValue = "-1"
.LoadingText = "Please wait..."
.ServicePath = "/ajax/InvestmentProcess.asmx"
.ServiceMethod = "GetTaxo"
End With
'Page.ClientScript.RegisterForEventValidation(CDDL.UniqueID)
targetDDL.Parent.Controls.Add(CDDL)
End Sub
When the web service method is called, it executes the following code. Based on the category, it gets the appropriate data from the adapter.
<WebMethod()> _
Public Function GetTaxo(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
log.Debug("GetSegmentTaxonomy(" + category + ") -> {" + knownCategoryValues + "}")
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim adapter As New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter
Dim rows As DataRowCollection
Select Case category
Case InvestmentEdit.ST_SEG_ARCH
rows = New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter().GetData().Rows
Case InvestmentEdit.ST_LOB
If kv.ContainsKey(InvestmentEdit.ST_SEG_ARCH) Then
log.Debug("found seg architecture - > " + kv(InvestmentEdit.ST_SEG_ARCH))
rows = New SegmentTaxonomyTableAdapters.LINE_OF_BUSINESSTableAdapter().GetData(kv(InvestmentEdit.ST_SEG_ARCH)).Rows
End If
End Select
If Not rows Is Nothing Then
Dim results As New List(Of CascadingDropDownNameValue)
For Each row As DataRow In rows
log.Debug("ROW >>>> " + row("lov_label").ToString() + " : " + row("lov_cd").ToString())
results.Add(New CascadingDropDownNameValue(row("lov_label"), row("lov_cd")))
Next
Return results.ToArray
End If
Return Nothing
End Function
There are about 5 drop downs I need to link together. The top-level drop down control (myDDL) loads fine if it is the only one linked like so:
CreateCascadingDropDown("MyCat",Nothing,myDDL)
But when I link a second drop down control, Internet Explorer gives a script timeout. If I keep allowing the script to run, it just keeps giving me the prompt. If elect to discontinue running the script, I get a Method Error 12031 or Error 500 (and yes, I have the ScriptService() declaration in my web service file). Any ideas on what's causing this?
It turns out I just needed to add the following control from the Ajax Control Toolkit:
<ajax:ToolkitScriptManager ID="tsm" runat="server" />
Instead of .TargetControlID = targetDDL.ID I needed to use:
.TargetControlID = targetDDL.UniqueId

Resources