dynamic value in textbox - asp.net

I have a text box like this:
<asp:TextBox ID="txtLogin" runat="server" Text='<%# strUserID %>'></asp:TextBox>
strUserID is a string value set in my codebehind and I bind the textbox to see the value. I tried with <%= strUserID %>, but it doesnt work for me. can you please tell me why?
Also, I have a hidden field like this:
<input id="hdnUserID" runat="server" type="hidden" value='<%=txtLogin.ClientID %>' />
and I have a function prints the hidden field value like this:
function CheckForValue()
{
var uid = window.document.getElementById('<%= txtLogin.ClientID %>').value;
alert(hdnUserID);
return false;
}
But this alert always prints as "[object]". Can anyone please explain this? Looks like <%= value %> doesnt work at all. But I have seen in my earlier projects where the existing code has these kinda lines!!

If your strUserID value is a member variable set in the code behind make sure it's access modifier is declared as at least protected or you will not be able to access it. Also the notation you want to use is <%= strUserID %> not <%# strUserID %> # is used to get the value of a databound dataItem.
Also in your second point I dont see the need for your hidden field. Can you not just use the following to get your textbox value?
function CheckForValue()
{
var textValue = window.document.getElementById('<%= txtLogin.ClientID %>').value;
alert(textValue);
}

Try taking the innerHTML or innerText values of the textbox for your message.

Related

How to use Request.Form to retrieve value when using masterpages

I have setup a hiddenfield control and a linkbutton on an aspx Masterpages content page.
<asp:HiddenField ID="HiddenField1" runat="server" value='<%# Eval("ID") %>'/>
<asp:LinkButton ID="LinkButton1" runat="server" postbackurl="orderhistorydetail.aspx">View</asp:LinkButton>
When trying to retrieve the value on the postback page using this code...
string oid = Request.Form[HiddenField1];
I am getting the error...
The name 'HiddenField1' does not exist in the current context.
Is this because of materpages? How can I fix this?
EDITED...
I viewed the source html that was generated for the page that has the hiddenfield control on it and this was the output...
<input type="hidden" name="ctl00$MainContentPlaceHolder1$ListView1$ctrl0$ctl00$HiddenField1" id="MainContentPlaceHolder1_ListView1_ctrl0_HiddenField1_0" value="12386026" />
Now, as for the code you originally gave me, I updated it to this...
HiddenField hf = Page.PreviousPage.Master.FindControl("MainContentPlaceHolder1").FindControl("ListView1").FindControl("HiddenField1") as HiddenField;
Still no luck. Am I getting close?
The page you are posting to has no knowledge of the Controls that are present on the previous page. You need to use FindControl for that.
HiddenField hf = Page.PreviousPage.Master.FindControl("ContentPlaceHolder1").FindControl("HiddenField1") as HiddenField;
string oid = hf.Value;
Or if you really want to use Request.Form you need to use the UniqueID.
string oid = Request.Form[HiddenField1.UniqueID];
First you must find the PlaceHolder of the Page that is using a Master Page and then the correct Control within the PlaceHolder.
If you want to check what all the Posted values are, use this:
foreach (string s in Request.Form.Keys)
{
Response.Write(s.ToString() + ": " + Request.Form[s] + "<br>");
}

Is there a way to insert text into a page without "Response.Write"?

I 'm trying to make a "login information" on the top panel, like "Welcome Back XXX", so I use
<% Response.Write(Session["username"]); %>
inside the aspx page.
It works, but is there anyway to use the variable directly without Response.Write here? It seems unnecessary.
There is a simple "shortcut" in the ASP.NET page syntax to Response.Write.
<%= Session["username"] %>
is functionally equivalent to
<% Response.Write(Session["username"]); %>
Typically you want to encode your session variables as HTML using Html.Encode, in case they contain characters which are not in the accepted HTML range. If you're using ASP.NET 4, you can use <%: %>, which is equivalent to Response.Write(Html.Encode(string)).
You can do it like this:
<%= Session["username"] %>
And if you use ASP.NET 4.0 you can automatically HTML encode the value by using this syntax:
<%: Session["username"] %>
put a asp.net label on your page, like
<asp:Label id=lblUserName runat="server" />
and on your codebehind page, on page_load event or on proper event
lblUserName.Text = String.Format("welcome back {0}",Session["username"]);
use a label and assign user name to it
In aspx (html code)
<asp:Label id=lblUserName runat="server" />
In aspx.cs (Code behind)
lblUserName .Text = "Welcome back"+Session["username"].ToString();
The correct way.
First is to check if the value is null
Second because you write it on a page, use the HTMLEncode to be sure that you avoid any type of injection, or problems.
now, if you like to use a Literal or a Label, or just direct write it, is up to you. If you going to place it inside an UpdatePanel you must use a Literal.
Now, if you use Literal avoid to set the ViewState to gain space from it, ether way you need to set it on PageLoad. And it will be
<asp:Literal runat="server" id="txtUserName" EnableViewState="false" />
and on page load.
if(Session["username"] != null)
{
Debug.Assert(Session["username"].ToString.Length > 0 , "Check out why I have zero user name");
txtUserName.Text = Server.HTMLEncode(Session["username"].ToString);
}

regex validator, required field

I'm trying to use the regular expression validator for a numeric ID field. The field needs to be a required field of any number. Currently, I'm using:
="\d{1,}"
Shouldn't this make it so the user has to at least enter 1 digit?? If I hit the submit button with the field empty, it passes validation and posts back.. But if I enter non-numeric characters, it errors fine. If I wanted zero or more occurrences, I'd use: ="(\d{1,})?"
Why isn't this working? Do I need to use this in combination with a Required Field Validator? That would suck ><
Make sure you set the property ValidateEmptyText to true or else the CustomValidator will not fire for empty text.
EDIT: You can attach a javascript function to the CustomValidator to accomplish this since I don't think a RegularExpressionValidator will fire against an empty control. I have created a basic example to illustrate the solution:
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("\\d{1,}");
args.IsValid = compare.test(args.Value);
return;
}
</script>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" Text="Test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Error!"
ControlToValidate="txtTest" ValidateEmptyText="true"
ClientValidationFunction="CheckMyText"></asp:CustomValidator>
I have tested it and it seems to work. Leave a comment if you require further assistance.
You still need to use a RequiredFieldValidator.
I'm not sure where the user is entering the IDs, but if the input field is TextBox control why don't you use something like this:
if (tbID.Text.Length != 0)
{
//Logic goes here
}
When user clicks submit, you need to make sure that not only empty strings are captured, below is a regex that looks for any whitespace(tab,space etc) + matches if character is not a digit(0-9)
Dim FoundMatch As Boolean
Try
FoundMatch = Regex.IsMatch(SubjectString, "\Dm/rld$/\s", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
'put your code here
Catch ex As ArgumentException
'syntax error in regular expression
End Try
I believe you'll need to use postback on your page, if you decide to use RequiredFieldValidator you can use above regex expression for that as well
Hth
In case someone is not using a CustomValidator then you can have a RequiredFieldValidator and RegularExpressionValidator for the same control. Found this solution here: http://forums.asp.net/t/1230931.aspx . Normally, this results in the error messages being displaced for the second validator but there is a way to fix that. You just have to set the Display property to dynamic for both the validators. Now the error messages for both the validators are displayed in the same location. Example code:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
ValidationExpression="regexExpression"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
Display="Dynamic"></asp:RequiredFieldValidator>`

Call HTML control in code behind

How can I get gridview HTML textbox value in .aspx.cs code?? E.g. :
<input id="Frequency" name="customerName" type="text" style="width: 44px" />
If i use the bellow code ,Then i can get the value on selectedIndex event.
string n = String.Format("{0}", Request.QueryString['customerName']);
I want to use bellow syntax.
TextBox_Label1 = (TextBox)e.Row.FindControl("Frequency");
i don't want to user the runat="server" on HTML control .
From Gridview i need to call a popup,Popup return a value ,I use the bellow code on javascript to do that
window.opener.document.getElementById("customerName").value = val;
window.close();
In my gridview .if i put the runat="server" then return value not set ,So i need to remove the runat="server".It also not work if i put the Asp:TextBox on Grid.Help me to Return popup value on gridview Asp:TextBox
Thanks!
Try a databinding expression:
<input id="Frequency" name="customerName" type="text" style="width: 44px"><%# String.Format("{0}", Request.QueryString["customerName"])%></input>
If you're having problems with this process and the difference is one is runat="server" and the other is not, I would suggest you need to look at your JavaScript to make sure that you have the proper element selection method. The rendered ClientID will be different from a standard html control ID. If you write your code so that the ClientID is injected into the JavaScript, you can keep the runat="server" and achieve your results. Standard html controls are not accessible from the code behind.

AutoCompleteExtender control in a repeater

I have an AutoCompleteExtender AjaxControlToolkit control inside a repeater and need to get a name and a value from the web service. The auto complete field needs to store the name and there is a hidden field that needs to store the value. When trying to do this outside of a repeater I normally have the event OnClientItemSelected call a javascript function similiar to
function GetItemId(source, eventArgs)
{
document.getElementById('<%= ddItemId.ClientID %>').value = eventArgs.get_value();
}
However since the value needs to be stored in a control in a repeater I need some other way for the javascript function to "get at" the component to store the value.
I've got some JavaScript that might help you. My ASP.Net AutoComplete extender is not in a repeater, but I've modified that code to detect the ID of the TextBox you are going to write the erturned ID to, it should work (but I haven't tested it all the way through to post back).
Use the value from 'source' parameter in the client side ItemSelected method. That is the ID of the calling AutoComplete extender. Just make sure that you assign an ID the hidden TextBox in the Repeater Item that is similar to the ID of the extender.
Something like this:
<asp:Repeater ID="RepeaterCompareItems" runat="server">
<ItemTemplate>
<ajaxToolkit:AutoCompleteExtender runat="server"
ID="ACE_Item"
TargetControlID="ACE_Item_Input"
...other properties...
OnClientItemSelected="ACEUpdate_RepeaterItems" />
<asp:TextBox ID="ACE_Item_Input" runat="server" />
<asp:TextBox ID="ACE_Item_IDValue" runat="server" style="display: none;" />
</ItemTemplate>
</asp:Repeater>
Then the JS method would look like this:
function ACEUpdate_CustomerEmail(source, eventArgs) {
UpdateTextBox = document.getElementById(source.get_id() + '_IDValue');
//alert('debug = ' + UserIDTextBox);
UpdateTextBox.value = eventArgs.get_value();
//alert('customer id = ' + UpdateTextBox.value);
}
There are extra alert method calls that you can uncomment for testing and remove for production. In a simple and incomplete test page, I got IDs that looked like this: RepeaterCompareItems_ctl06_ACE_Item_IDValue (for the text box to store the value) and RepeaterCompareItems_ctl07_ACE_Item (for the AC Extender) - yours may be a little different, but it looks practical.
Good Luck.
If I understand the problem correctly, you should be able to do what you normally do, but instead of embeding the ClientId, use the 'source' argument. That should allow you to get access to the control you want to update.
Since you are using a Repeater I suggest wiring the OnItemDataBound function...
<asp:Repeater id="rptResults" OnItemDataBound="FormatResults" runat="server">
<ItemTemplate>
<asp:PlaceHolder id="phResults" runat="server" />
</ItemTemplate>
</asp:Repeater>
Then in the code behind use something like
`Private Sub FormatResults(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
Dim dr As DataRow = CType(CType(e.Item.DataItem, DataRowView).Row, DataRow) 'gives you access to all the data being bound to the row ex. dr("ID").ToString
Dim ph As PlaceHolder = CType(e.Item.FindControl("phResults"), PlaceHolder)
' programmatically create AutoCompleteExtender && set properties
' programmatically create button that fires desired JavaScript
' use "ph.Controls.Add(ctrl) to add controls to PlaceHolder
End Sub`
Voila

Resources