Programatically adding MenuItems triggers Page_load in target URL - asp.net

I am adding menu items programmatically so I can control which ones appear based on the role of the user. My problem is that every menu item I add behaves as if it has been clicked on during the load. Stripped to bare bones, here is the simplified code:
Public Class test2
Inherits System.Web.UI.Page
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If Not IsPostBack Then
CreateMenu()
End If
End Sub
Private Sub CreateMenu()
MainMenu.Items.Add(New MenuItem("Home", "", "/Peak.aspx"))
End Sub
End Class
The test2.aspx contains:
<form id="form1" runat="server">
<asp:Menu ID="MainMenu" runat="server" >
<Items>
</Items>
</asp:Menu>
</form>
This is all the code in Peak.aspx.vb:
Public Class Peak
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
MsgBox("This should not appear but does!!")
End Sub
End Class
The Peak.aspx Page_Load is being loaded and the message box displayed, when test2 is set as the start up page. My real code has several menu items added and CreateMenu causes ALL the page_Loads to be being triggered with a large overhead!
Is this a bug or something I can switch off, and is there a workaround?

You're using this constructor https://msdn.microsoft.com/en-us/library/b00a9c35.aspx
public MenuItem(
string text,
string value,
string imageUrl
)
If you look at it carefully, your third parameter sets imageurl, thus triggering Page_Load event when it tries to load the url. Maybe you wanted to use this overload with 4 parameters? https://msdn.microsoft.com/en-us/library/70k2h50z.aspx
public MenuItem(
string text,
string value,
string imageUrl,
string navigateUrl
)

Related

pass parameters with OnServerClick vb.net

I am really new in VB and It is hard to get my head around it especially working with non-MVC projects, so i wish i can find my answer here.
I want to pass arguments with the OnServerClick the code below is the html code:
<a id="Anchor1" OnServerClick="LogIn" runat=server> Click Me </a>
and the method in the server is below:
Protected Sub LogIn(sender As Object, e As EventArgs)
e.value
End Sub
I want to pass parameters(args) to the LogIn method??
I don't want to use any VB or razor buttons or anchor tags i want to use the html tags with the onserverclick attribute. is that possible??
thank you in advance.
You can add custom attribute to aspx <a> like this.
<a id="Anchor1" OnServerClick="LogIn" runat="server" customdata="hello"> Click Me </a>
And get that value in LogIn.
Protected Sub LogIn(sender As Object, e As EventArgs)
Dim myButton = CType(sender, HtmlAnchor)
Dim valuepassedfromUI = myButton.Attributes("customdata")
Dim buttonID = myButton.ClientID
End Sub
, See the screenshot.

Add onclick event to the radio button that added dynamically

I'm creating an online exam page with 30 radiobuttons that are created dynamically at runtime.
How will I get the click event of each radiobutton and tag it in my method that I will check if the next question is need to be jump or escape.
Example:
If I'm in question 10 and answer = "Yes", redirect me to Question 15, else go to the next question
HTML code-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="RadioButtonsPanel" runat="server" />
</form>
</body>
</html>
VB Code-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Add each radio button
AddNewRaduiButton("MyRadio1")
AddNewRaduiButton("MyRadio2")
AddNewRaduiButton("MyRadio3")
AddNewRaduiButton("MyRadio4")
End Sub
Private Sub AddNewRaduiButton(ByVal name As String)
' Create a new radio button
Dim MyRadioButton As New RadioButton
With MyRadioButton
.ID = name
.AutoPostBack = True
.Text = String.Format("Radio Button - '{0}'", name)
End With
' Add the click event to go to the sub "MyRadioButton_CheckedChanged"
AddHandler MyRadioButton.CheckedChanged, AddressOf MyRadioButton_CheckedChanged
Page.FindControl("RadioButtonsPanel").Controls.Add(MyRadioButton)
End Sub
Protected Sub MyRadioButton_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
' Convert the Sender object into a radio button
Dim ClickedRadioButton As RadioButton = DirectCast(sender, RadioButton)
' Display the radio button name
MsgBox(String.Format("Radio Button {0} has been Updated!", ClickedRadioButton.ID))
End Sub
Use the following statement:
AddHandler radioButton.Click, AddressOf instance.MethodName
Refer to How to: Dynamically Bind Event Handlers at Run Time in ASP.NET Web Pages
Also consider using an anonymous sub (VB2010 only) to write the event handler inline
AddHandler radioButton.Click,
Sub(s As Object, e As EventArgs)
MessageBox.Show("Awesome!")
End Sub
Adapted from here
You can also use closures...

Events Firing Out Of Order Asp.Net

I have a system setup as follows:
User Control Called "Main" when I click a button in "Main" another user control (user control "A", user control "B", user control "C") is populated inside a placeholder of "Main" depending on some logic either A,B, or C is populated.
User controls A,B,C have many buttons on them as well. They Also have a placeholder to contain either user control x, user control y, user control z depending what is clicked inside user control "A" for example.
Main loads controls (A,B, or C) into its placeholder no problem, but when I click a button in A,B,or C to load their placeholder with x,y, or z the whole control (A,B, or C) dissappears.
I understand this has to do with viewstate not holding dynamic controls during a postback. So what I did was explictly called viewstate on the controls loaded into main (A,B,C). when they are loaded I save an entry of what was loaded like this ViewState("lastLoaded")='A' for example. When a postabck occurs (i.e. clicking a button in A) I reload the whole control A.
This is what happens:
I click a button in user control "A"
Postback occurs
User control "A" is reloaded because of the viewstate("lastloaded")
Then I have to click the button in "A" again at that time the button_click event fires
Can someone please help me fix this.
'Here is Main.ascx
Partial Class Main
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
ViewState("name") = "ControlA2.ascx"
AddControl(ViewState("name").ToString())
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If ViewState("name") <> String.Empty Then
AddControl(ViewState("name").ToString())
End If
End Sub
Public Sub AddControl(ByVal name As String)
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl(name)
PlaceHolder1.Controls.Add(toAdd)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
ViewState("name") = "ControlB.ascx"
AddControl(ViewState("name").ToString())
End Sub
End Class
'Here is Main designer
Main
asp:Button ID="Button1" runat="server" Text="Add Control A"
asp:Button ID="Button2" runat="server" Text="Add Control B"
asp:PlaceHolder ID="PlaceHolder1" runat="server">
'Here is ControlA2.ascx
Partial Class ControlA2
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl("ControlX.ascx")
PlaceHolder1.Controls.Add(toAdd)
End Sub
End Class
'Here is ControlA2 designer
I am Control A
Add Control X
asp:Button ID="Button1" runat="server" Text="Add Control X"
asp:PlaceHolder ID="PlaceHolder1" runat="server"
/asp:PlaceHolder
'Here is ControlB.ascx
Partial Class ControlA2
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl("ControlZ.ascx")
PlaceHolder1.Controls.Add(toAdd)
End Sub
End Class
'Here is ControlB designer
I am Control B
Add Control Z
asp:Button ID="Button1" runat="server" Text="Add Control Z"
asp:PlaceHolder ID="PlaceHolder1" runat="server" /asp:PlaceHolder
'Here is ControlX.designer
asp:Label ID="Label1" runat="server" Text="Label">I AM CONTROL X /asp:Label
'Here is ControlZ designer
asp:Label ID="Label1" runat="server" Text="Label">I AM CONTROL Z /asp:Label
I've created a project based on your code and I've managed to recreate the issue.
When I initially run it and click on the Add control A button the Main control will load Control A and note this in the viewstate. Control A's button to add Control X will now appear with an id of Main1_ctl00_Button1. When clicking on this button Main's page load will add Control A back to it's placeholder and Control A's button click event will fire. If you now click Main's Control A button again the problem arises. Main's page load method will look at the Viewstate and add control A to the placeholder. Then Main's button click event will then fire clearing the placeholder and re-adding control A. When the form is displayed Control A's button to add Control X will now have an id of Main1_ctl01_Button1 as it was the second control to be generated in the code behind. Now when you click on the button to add control x Main's page load will add Control A again but as it's id will be Main1_ctl00_Button1 and the click event came from a button with an id of Main1_ctl01_Button1 the event will not fire.
To fix this you will have to avoid the duplication of control creation the second time around. You could do this by checking the requests form collection during the page load to see which button was pressed although this is not a very elegant solution. You will need to ensure that the buttons on the Main control have a unique text value for this to work.
Hopefully someone else may be able to come up with a more elegant solution:
Dim mainButtonClick = False
For index As Integer = 0 To Request.Form.Count
If Request.Form(index) = "Button A" Or Request.Form(index) = "Button B" Then
mainButtonClick = True
End If
Next
If Not IsPostBack And Not mainButtonClick And ViewState("name") <> String.Empty Then
AddControl(ViewState("name").ToString())
End If
Please excuse any errors in this code as I am not a VB.NET programmer.

Using aspx controls in base class

I've got two aspx pages which are very similar and have various identical functions in the code behind. I'd like to create a base class which both the code behind classes derive from. Is it possible for the base class to access the controls on the aspx page. For instance:
class base
inherits System.Web.UI.Page
Sub prepareScreen()
'txtName is a text box on the aspx page
Me.txtName.text = "George"
end sub
end class
class codeBehind
inherits base
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
prepareScreen()
end sub
end class
Somewhat understandably the code fails to compile with:
'txtName' is not a member of 'clsbase'
Is it possible to link the two together?
You need to declare the control as a property of the base class. Then in the ASP markup, use the CodeFileBaseClass attribute.
The MSDN reference is no longer available.
class base
inherits System.Web.UI.Page
Protected Property txtName() As TextBox
Sub prepareScreen()
'txtName is a text box on the aspx page
Me.txtName.text = "George"
end sub
end class
class codeBehind
inherits base
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
prepareScreen()
end sub
end class
<%# page CodeFileBaseClass="base" inherits="codebehind" ... %>
It would be better if you refactor your code, so that you have no need to do something like this.
One better idea will be if you create a virtual method in the base class, which you can override in your child page(s), and set the value of your textbox, as you'll have an easy access to the textbox.
You could use FindControl, eg.
TextBox txtName=FindControl("txtName");
which would find the control on the rendered page even though it was rendered by the descendant class. Though this is breaking the point of OO and separation of function/data somewhat.
You can use ((TextBox)Page.FindControl("txtName")) to get the textbox. Be careful because if you use this base class else where the control might not exist
In response to your clarification:
You could Create a property:
protected TextBox txtName
{
get{return (TextBox)Page.FindControl("txtName");}
set{Page.FindControl("txtName") = vale;}
}
Or Create a Virtual property:
protected virtual TextBox txtName{get;set;}
In this case you would have to override it at your main class
protected override TextBox txtName{/*same as above*/}

Masterpage with Asp.net Ajax problem

I placed the scritmanager to masterpage. "scriptmanager1"
There is an updatepanel in the masterpage shows total. "updatepanel1"
In the contentpage I have nested listviews. the "listview2" inside the "listview1" has itemtemplate with a linkbutton called "addtoTotal"
I want to update the updatepanel1 inside the masterpage when user clicks to addtoTotal button.
updatepanel1's update mode is conditional.
How can I do this.
Firstly I could not findcontrol addtoTotal linkbutton.
Second how can I register this button to update updatepanel1
I want to triger the conditional updatepanel from the contentpage.
I tried to do something like this
protected void Page_Load(object sender, EventArgs e) { ScriptManager1.RegisterAsyncPostBackControl(myControl);
}
I could not. Because I don't know where to write this RegisterAsyncPostBackControl code. I could not findcontrol the linkbutton. I am not sure about the way I am trying to solve this is right way.
You can put a subroutine on your master page that updates the panel and you can call it from the content page like so.
Public Partial Class _Default1
Inherits System.Web.UI.MasterPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub updatedpage()
updatepanel1.update()
End Sub
End Class
Public Partial Class _Default5
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
CType(Me.Master, _Default1).updatedpage()
End Sub
End Class
for finding the addtoTotal button I believe you are gonna have to do the following in the code behind
ListView listview2 = (ListView)listview1.FindControl("listview2");
LinkButton addtoTotal = (LinkButton)listview2.FindControl("addtoTotal");
you should be able to find the listview2 within the first listview and then find the LinkButton within listivew2
I'm not quite sure that I understand your question but it seems to me that this article should point you in the right direction

Resources