Acessing Items on a Masterpage from a Child page - asp.net

I have a <ASP:Label ID="lblDashboardLink" runat="server" /> located on a MasterPage named MasterBase.
From a page using this MasterPage, how can I access this label or any other items I need?
'VB.NET
'(From the child .aspx page)
Master.FindControl("lblDashboardLink"). <-- but don't see an option to change URL
I've been googling and I keep finding this same method, but it's focusing more on User Controls it looks like... Can anyone guide me in the right direction here?? I'm so used to MVC!

Master.FindControl("lblDashboardLink") always returns a Control (see MSDN). So all you have to do is cast it to Label. Then you may access any properties of a Label. Anyway there is no URL property in a label...
CType(Master.FindControl("lblDashboardLink"), Label).Text = "your value"

Try this:
CType(Master.FindControl("lblDashboardLink"), Label).Text = "some url"

Related

using postbackurl to pass variables without referencing ctl00$MainContent

I'm hoping there's a cleaner way of doing this. My source page markup has some simple inputs and a submit button:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" />
<asp:TextBox runat="server" ID="TBPostDateTo" placeholder="Present" />
...
<asp:Button ID="BtnDetailedResults" PostBackUrl="~/Auth/ResultsDetail.aspx" runat="server" Text="View Detailed Results" />
On my target page, I'm trying to reference those controls and use them as datasource select parameters. So far the only way I've found to do that is to use the long asp generated names "ctl00$MainContent$TBPostDateFrom" and "ctl00$MainContent$TBPostDateTo":
SDSDetailedResults.SelectParameters.Add("PDFrom", Request.Form["ctl00$MainContent$TBPostDateFrom"]);
SDSDetailedResults.SelectParameters.Add("PDTo", Request.Form["ctl00$MainContent$TBPostDateTo"]);
Is there a way I can reference those controls without using the long ct100$...? Or a way to reference the controls directly? I'm guessing if sometime down the road I change my master page, or content controls, these references would get messed up.
I've tried adding using adding the ClientIDMode=Static to the inputs like:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" ClientIDMode="Static" />
But that appears to only change the ID. On my target page, I'm still unable to reference it without using the ct100$....
I've also tried using the Page.PreviousPage method, but the objects end up empty:
if (Page.PreviousPage != null)
{
//post date
TextBox PostDateFrom = (TextBox)Page.PreviousPage.FindControl("TBPostDateFrom");
TextBox PostDateTo = (TextBox)Page.PreviousPage.FindControl("TBPostDateTo");
//at this point both PostDateFrom and PostDateTo are empty, if I do this:
SDSDetailedResults.SelectParameters.Add("PostDateFrom", PostDateFrom.Text);
SDSDetailedResults.SelectParameters.Add("PostDateTo", PostDateTo.Text);
// I get an IIS error saying the object references dont' exist, or are null
}
}
Thanks in advance, any help or guidance is much appreciated!
For a search page, I would recommend using the QueryString to pass information to your later page, rather than trying to reference the controls from the previous page.
This will be especially useful if you want to use this functionality from different technologies. You won't have to worry about where the request came from.
SearchPage.aspx:
//Button Click:
var page = "ResultsDetail.aspx";
var url = String.Format("{0}?TBPostDateFrom={1}&TBPostDateTo={2}", page, TBPostDateFrom.Text, TBPostDateTo.Text);
Response.Redirect(url);
ResultDetails.aspx:
var from = DateTime.Parse(Request.QueryString["TBPostDateFrom"]);
var to = DateTime.Parse(Request.QueryString["TBPostDateTo"]);
//Do search based on parameters
For more information: MSDN - How to: Pass Values Between ASP.NET Web Pages

how to change the title of the confirmation in asp

I have added a confirmation dialog before deleting an item in asp.net web page.
Here's my coding.
OnClientClick="return confirm('Are you sure you want to delete this Contact Record?');"
It gives the default title as "The page at local host:49456 says:"
I need to change that default title of this dialog box.My default browser is Google chrome.
Can somebody help me???
Thanx in advance.
Give the Header needed like this.
OnClientClick="return confirm('Are you sure you want to delete this Contact Record?','Your Title');
note: when tweaking page title - can't change it here if the aspx page sets it to "". so, in the .aspx page set it to something other than empty string; e.g.:
Page.Title = "Some New Title";

ASP.NET TextBox (HTML input field) populates with username automatically when form loads

I have a TextBox control in a form which is still pulling in data when the HTML form renders. I tried setting the AutoCompleteType to "None" but I think that just controls whether or not it will find previously entered data for that field, not what actually fills into that input field when the page loads. Why would this textbox be pulling in data? It's causing another larger issue. This TextBox is inside of a control (*.ascx file). It's loaded from another control dynamically--not sure if that matters. It's only happening in Mozilla Firefox. When I check txtKeywords.Text in the Page_Load event of the control that contains the TextBox, the value is null. So the value is obviously coming from the browser, not the server. What would cause this??
<asp:TextBox id="txtKeywords" runat="server" Width="125px" AutoCompleteType="None" autocomplete="False"></asp:TextBox>
Rendered HTML:
<input type="text" style="width: 125px;" autocomplete="False" id="ExplorerPageHtmlLeft_ctl01_txtKeywords" name="ExplorerPageHtmlLeft$ctl01$txtKeywords" gtbfieldid="77">
Parent control code behind (searchPanel1 control contains the TextBox):
Private Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles MyBase.Load
navigation1 = CType(LoadControl("ExplorerNavigation1.ascx"), ExplorerNavigation1)
searchPanel1 = CType(LoadControl("SearchPanel.ascx"), SearchPanel)
navigation2 = CType(LoadControl("ExplorerNavigation2.ascx"), ExplorerNavigation2)
Me.PlaceHolder1.Controls.Add(navigation1)
Me.PlaceHolder1.Controls.Add(searchPanel1)
Me.PlaceHolder1.Controls.Add(navigation2)
End Sub
I couldn't find any suspicious JavaScript yet, after Massimiliano Peluso's comment. However, I did notice that the value in this input field is ALWAYS the same as the user's id. The value of the "gtbfieldid" attribute on the TxtUser field always seems to change when I inspect the element in Firebug. This TxtUser field is always different from our txtKeywords input field. They are on different pages. And they seem to populate with different values each time. So I didn't see a correlation there. I still don't know what this attribute is for. This attribute doesn't show in Internet Explorer, so it must be inserted into Firefox for some reason.
<input type="text" id="TxtUser" name="TxtUser" gtbfieldid="37">
Thanks to Johnny #5's input, we proved that the server was not setting this text. This is not the answer to my question, but this was very helpful. I put a breakpoint into the setter, and it did not get called. Only the getter got called. To clarify things, this is a custom web server control (.vb file), NOT TO BE CONFUSED with a custom user control (.ascx file, *.ascx.vb file and sometimes *.ascx.Designer.vb file). I added Render event to this class. I also had to import 2 namespaces. The next thing I'd like to figure out is a way to be able to extend the browser's ability to set text in this field (via client side), like we did below for the server side. That would be a frickin' awesome methodology for this type of problem. Not sure if Firebug has that capability though. I still don't know what's setting this text. So my question is still up for grabs.
Imports System.Web
Imports System.Web.UI.WebControls
Public Class MyTextBox
Inherits System.Web.UI.WebControls.TextBox
Public Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
End Set
End Property
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
End Sub
End Class
In my page where I'm implementing this custom web server control, I need to register this class.
<%# Register Assembly="Acu.LIMS.UI.Web" Namespace="Acu.LIMS.UI.Web" TagPrefix="MyTextBox" %>
<MyTextBox:MyTextBox id="txtKeywords" runat="server" Width="125px" AutoCompleteType="None" AutoComplete="False"></MyTextBox:MyTextBox>
Well, I'm not crazy! It's not server side code and it's not client side code causing this. It's Mozilla Firefox's > Options > Security > Remember password checkbox causing the problem. BUT I'M STILL CONFUSED. :-\
On the computer causing the issue, I kept toggling this checkbox, and could not get the browser to ask me the question, "Do you want Firefox to remember your password?" (don't remember the exact wording). But on another computer, I got asked immediately. And when I clicked "Remember" and went to that page, "x" shows in this input field (aka TextBox web control). Both my user name and password are both "x", so I'm not sure which it is pulling. Despite the value it pulls, my culprit TextBox doesn't have either id (of the user id or password) as it's id. Next question: How does Firefox determine when to fill in the username and password? One interesting thing about this form is that another field does have the password textbox, but I DO NOT have the user id in this form. I wonder if Firefox puts the user name in the first field it finds??
=======================
Answer
So I put in a dummy field in the SearchPanel control, and guess where my user name filled in. I was reading on this link about the Mozilla Password Manager, and apparently Mozilla uses its intelligence to determine the best place to put the user id (sometimes referred to as user name). In my case, I have a label for the user name (not the user id) in my Authentication control, but I don't want a user id field. Since the user is already logged in, they shouldn't be entering any user id. So that's why the user name label is in front of the password field. We audit changes in our application, so that is the purpose for having it inside the application.
https://wiki.mozilla.org/Firefox%3aPassword_Manager
So I did a test to validate Mozilla's functionality. I put another dummy field after the older culprit TextField (with id "txtKeywords", so that it's placement is the last input field preceding the password input field. And guess where Mozilla Firefox put the user id? Yep, in the dummy TextBox/input field. When I turn off the "Remember password for sites" option under Mozilla > Options > Security, it doesn't populate, nor does my password field. So this is my answer. I guess for now, I'll just put a hidden TextBox field in my Authentication control so Mozilla populates that one instead, but is not visible.
SearchPanel.ascx control:
<tr>
<td nowrap class="categoryverticalNav">
<asp:Label id="lblSearch" runat="server">Search</asp:Label><BR>
<asp:DropDownList id="ddlCategory" runat="server" Width="164px"></asp:DropDownList><BR>
<asp:TextBox id="txtKeywords" runat="server" Width="125px" AutoCompleteType="None" AutoComplete="False"></asp:TextBox>
<asp:TextBox id="TextBox1" runat="server" Width="125px" AutoCompleteType="None" AutoComplete="False"></asp:TextBox>
<asp:Button id="btnGo" runat="server" Width="28px" Text="Go" CausesValidation="False" />
</td>
</tr>
Yep, putting in a hidden input field solved it. I suppose I could have either put in a TextBox also, but I just chose an input field with runat="server".. since the CLR doesn't need to interact with it in ASP.NET. Once I did that, the "x" (user id) disappeared from the SearchPanel control txtKeywords input field. :-)
<td>
<b><asp:Label ID="LblUserDisplayName" Runat="server" EnableViewState="False"></asp:Label></b>
</td>
<td>Password</td>
<td>
<input runat="server" type="text" style="display:none;">
<asp:TextBox id="TxtPassword" Runat="server" Width="80" EnableViewState="False" TextMode="Password"></asp:TextBox>
</td>
Simple solution: set autocomplete property of text box to "off"
<asp:TextBox id="TxtPassword" Runat="server" Width="80" autocomplete="off" TextMode="Password"></asp:TextBox>
In the ASP.NET life cycle, there are two events which are responsible for the maintain data after postback. One is LoadViewState and another is LoadPostBackData. If a control which implement IPostBackDataHandler interface gets loaded by the values from Http Post data in the LoadPostBackData event. A TextBox control does not get its value from the view state but from the post data in the form in this event. So even if you disable view state for the TextBox control, it can get its value from the HTTP post data if it implements IPostBackDataHandler interface.
If Page.IsPostBack(){
yourTextBox.Text=string.empty;
}
http://forums.asp.net/t/1104194.aspx/1
have also a look at the below:
http://www.codeproject.com/KB/aspnet/ASPViewStateandPostBack.aspx
If you want to find if the text is setted on server side, you could try this :
public class MyTextBox : System.Web.UI.WebControls.TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
}
Use this text box inside your user control instead of the original one, then put a break point on the setter, and check the call stack when you got there.
MacGyver's Notes:
Adding some clarification. This does NOT answer my question, but was VERY useful in proving that the text was not getting set on the server side. This is a custom web server control (.vb file), not to be confused with a custom user control (.ascx file, *.ascx.vb file and sometimes *.ascx.Designer.vb file). I added Render event to this class. I also had to import 2 namespaces.
Imports System.Web
Imports System.Web.UI.WebControls
Public Class MyTextBox
Inherits System.Web.UI.WebControls.TextBox
Public Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
End Set
End Property
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
End Sub
End Class
In my page where I'm implementing this custom web server control, I need to register this class.
<%# Register Assembly="Acu.LIMS.UI.Web" Namespace="Acu.LIMS.UI.Web" TagPrefix="MyTextBox" %>
<MyTextBox:MyTextBox id="txtKeywords" runat="server" Width="125px" AutoCompleteType="None" AutoComplete="False"></MyTextBox:MyTextBox>
See the bottom of my question for the Answer. It's all explained. Essentially Mozilla Firefox Password Manager places the user id into the last input field preceding the stored input field (based on what's stored in the Mozilla Firefox Password Manager). So I'm just going to place a hidden dummy textbox (or input) field inside my Authentication control that precedes my password input field.
This article has one quote that sort of explains it, but I think I have a better explanation.
https://wiki.mozilla.org/Firefox%3aPassword_Manager
Quote from link above:
"Then uses the usernamefield/passwordfield values as hints to find the appropriate elements within a webpage by matching them to the "name" attribute."
Copy & paste below code into your page head section.
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/jscript">
$(document).ready(function () {
setTimeout(function () {
$("input[type='password'],input[type='text']").val('');
}, 50);
});
</script>

hyperlink.NavigateUrl getting changed on master page (possibly by ResolveUrl() )

I have a hyperlink that in certain cases I want to change to show a jquery popup, but I'm having a strange problem when doing it on a master page. The following works in a regular page:
hyp1.NavigateUrl = "#notificationPopup";
Which renders as:
<a id="ctl00_hyp1" href="#notificationPopup">Example</a>
This is exactly what I want. The problem is with the exact same code on a hyperlink on the master page it renders as:
<a id="ctl00_hyp1" href="../MasterPages/#notificationPopup">Example</a>
It looks like it might be running the navigateUrl through ResolveClientUrl() or something when I'm setting it on the master page. I've tried swapping the <asp:hyperlink for a <a href runat=server, but the same thing happens.
Any ideas?
There is a note on MSDN Control.ResolveClientUrl method description.
The URL returned by this method is
relative to the folder containing the
source file in which the control is
instantiated. Controls that inherit
this property, such as UserControl and
MasterPage, will return a fully
qualified URL relative to the control.
So the behavior of master page in your exampe is fully predictable (although this is not a very comfortable to work with). So what are the alternatives?
The best one is to set the <a> as a client control (remove runat="server"); should work like a charm even in a master page:
Example
In the case if this control should be server side only: you could just build an URL from your code behind by using UriBuilder class:
UriBuilder newPath = new UriBuilder(Request.Url);
// this will add a #notificationPopup fragment to the current URL
newPath.Fragment = "notificationPopup";
hyp1.HRef = newPath.Uri.ToString();
Create a hidden field on your form and set the value to where you want to navigate / the url of the hyperlink instead of the hyperlinks navigate url. Then call the onclick method of the hyperlink in javascript and set the hyperlink there before the browser does the actual navigation.
<html><head><title></title></head>
<script type="text/javascript">
function navHyperlink(field)
{
field.href = document.getElementById('ctl00_hdnHypNav').value;
return true;
}
</script>
<input type="hidden" id="hdnHypNav" value="test2.html" runat="server"/>
<a href="" onclick="navHyperlink(this);" >click here</a>
</html>
Code behind would be:
hdnHypNav.value = "#notificationPopup";
You could also just try setting the url after the postback with below code, i.e. replace your code behind line with this one but I am not sure if it will work...
ScriptManager.RegisterStartupScript(this,this.GetType(),"SetHyp","$('ctl00_hyp1').href = '#notificationPopup';",True)
I found another way to solve the problem.
hyp1.Attributes.Add("href", "#notificationPopup");
Seeing as the whole reason I replaced my static hyperlink with a runat="server" one was to benefit from automatic resource-based localization, none of these answers served my needs.
My fix was to enclose the hyperlink in a literal:
<asp:Literal ID="lit1" runat="server" meta:resourcekey="lit1">
Example
</asp:Literal>
The downside is if you need to programmatically manipulate the link, it's a bit more annoying:
lit1.Text = String.Format("Example", HttpUtility.HtmlAttributeEncode(url));

ASP.NET: checkboxlist with textbox?

I'm working in ASP.NET and I have a CheckBoxList where I want one of the options to be basically like "Other: _." So I need to include a textbox where the user can fill in their own option. It doesn't seem like there's a way to include a textbox inside of a checkboxlist, however. What's the best way to make this work?
-UPDATE-
If using a separate textbox control, how do I position it so it will align correctly with the checkbox?
Make the textbox a separate control on the page, then in your codebehind, check to see if other is checked. If it is, pull the value of the textbox, and use that.
To answer the question in your edit: You'll have to play with the CSS of the page to get it positioned correctly. How you do it depends on the layout of the page, among other things. I recommend posting some of the HTML from your page in another question and ask about how to position them.
What #Kyle Trauberman said...
Make the textbox a separate control on
the page, then in your codebehind,
check to see if other is checked. If
it is, pull the value of the textbox,
and use that.
Plus use javascript to hide or gray out the option unless the checkbox is selected.
string test="";
<asp:CheckBoxList ID="chk_list" runat="server">
<asp:ListItem Value="00">xxxx</asp:ListItem>
</asp:CheckBoxList>
<asp:TextBox ID="other" runat="server"></asp:TextBox>
inside the for loop
if (chk_list.Items[i].Value == "00")
{
test +=chk_list.Items[i].Text + other.Text;
}

Resources