using postbackurl to pass variables without referencing ctl00$MainContent - asp.net

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

Related

Accessing/Setting the property value of an object property of an ASP.NET User Control - Using Decalarative Syntax

I feel like I recall from days gone by an article explaining how to DECLARATIVELY set the value of the property of an object, exposed as the property of an ASP.NET User Control.
My situation is that I have a user control which contains a LinkButton, amongst other things, of course. I would like the consumer of the User Control to be able to set the TEXT value of the link button in the declarative syntax used to implement the User Control.
Here is the User Control (designer)...
<div id="toolbar">
<ASP:LinkButton runat="server" id="btnFirst" />
<ASP:LinkButton runat="server" id="btnSecond" />
<ASP:LinkButton runat="server" id="btnThird" />
<ASP:LinkButton runat="server" id="btnFourth" />
</div>
Here is the property as defined in the code behind of the User Control ...
public partial class Lookuptoolbar: UserControl
{
public LinkButton FourthButton
{
get { return (this.btnFourth); }
}
}
When I include the control in a page I EXPECTED to be able to set the TEXT of my FOURTH button using the following DECLARATIVE syntax ...
<UC:MyControl id="uc1" runat="server" FourthButton_Text="Click Me!"/>
I had read once somewhere, a long time ago, that you could access the properties of an object (exposed as the property of a user/server control) by using the underscore syntax. This is not working for me at all. Is this no longer allowed or am I missing something? IS there ANY way of doing this?
Thank You,
Gary
Ok ... for any who might be interested I think I have found the answer, or at least the beginnings of it. The syntax would be with a HYPHEN and not an underscore. So the correct syntax would be.
<UC:MyControl id="uc1" runat="server" FourthButton-Text="Click Me!"/>
When accessing the "subproperties" of complex types there may be more to it; I haven't gone into it in detail, but the book "Developing Microsoft ASP.NET Server Controls and Components" by Microsoft Press (ISBN 0-7356-1582-9) discusses this on pages 218-222.
If anybody learns anything more I would love to hear about it, otherwise I hope that this helps somebody out there!
-Gary
I have never heard of or seen anybody use the method you talk about (using underscore for accessing object properties in the declarative syntax).
One way to do what you want would be to expose a FourthButtonText property on the user control that interacts with the LinkButton's text property:
public string FourthButtonText
{
get { return this.btnFourth.Text; }
set { this.btnFourth.Text = value; }
}

how to check a particular asp.net validation control is valid?

In a web form there are different asp.net validation controls. Is it possible to check a particular validation control is valid ? For example on leaving focus of textbox, first I will check requiredFieldValidatorUserName is valid ? If it is valid then I will check on server using ajax that this user name is not booked already.
Edit:
Explaination: I want to check validity (that input was valid) of a validation control on client side.
Please guide.
All validator controls implement IValidator which contains the IsValid property.
myValidatorControl.IsValid
The best way would be to use a CustomValidator with client side code, as this will display all the error messages, block form submission and also ensure that the validation is repeated at the server side - remember, just because you have client-side validation available, doesn't mean the user's seen it: Always validate your input at the server as well.
Your CustomValidator would then be coded to call the Ajax methods, and would show the error messages correctly to the client:
<asp:Label ID="UserNameLabel" AssociatedControlID="UserName" runat="server">
UserName *:</asp:Label>
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" EnableClientScript="true"
ErrorMessage="You must supply a username!" />
<asp:CustomValidator ID="UserNameCustom" runat="server"
ControlToValidate="UserName"
ClientValidationFunction="CheckExisting"
OnServerValidate="UserNameCustomValidate"
ErrorMessage="Username already taken" />
And your ClientValidationFunction should look something like:
<script type="text/javascript">
function CheckExisting(source, arguments) {
// Pass the arguments.Value to your AJAX call:
if (ajaxCallUserNameTaken(arguments.Value)) {
arguments.IsValid = false;
}
}
</script>
(Obviously, you'll need to write the ajaxCallUserNameTaken method to call your page method/web service/etc.)
Doing it this way will ensure that the validation methods happen as expected; this will get called whenever the user tabs out of the textbox leaving a value (it won't get called if the textbox is empty), and will ensure that the user can't submit the page until they supply a unique value. You'll also want to create the method referenced in OnServerValidate to ensure that the value's good once it hits the server too - this should call the same code that the AJAX endpoint uses to reduce duplication of code, etc.
I was originally going to suggest that you could use the Page_Validators object on the client-side to do some checking in the onBlur event, but I don't really think this is suitable here as it results in more pain:
It assumes that although there might be more than one validator on the page, there's only the RequiredFieldValidator on the control we're checking
The RequiredFieldValidator isn't fired during OnBlur if a user moves out of a control without setting a value - only if they set and clear the value, so even if isvalid is true, you need to check for an empty string!
You could do this by setting the ValidationGroup for the Validator control that you want to treat as separate from the others. Make sure it matches the ValidationGroup of the control it's validating (your username field).
I have just faced the same issue and I Set CausesValidation="true" to the textbox control and it worked. Just give it a try :)
I have been messing around with this around for a bit and found a rather easy (not so efficient) solution to handle this using jQuery.
Use this function to check the validity of your control:
function validateControl() {
return $('#YOUR_VALIDATOR_ID').css("visibility") == "visible"
if you're using Display="Dynamic" on your validator then the function is like so:
function validateControl() {
return return $('#YOUR_VALIDATOR_ID').css("display") == "inline"
Be sure to check the true ID of your validator if you're using a Masterpage, as it will be different than the one in your IDE. Do so by viewing the page source in your browser.
The best solution will be of course to validate your form in some other way, using JavaScript or a CustomValidator that lets you write your own code.

How can you tell if form runat=server has been set?

When coding an Asp.Net page, you generally add a runat attribute in the aspx:
<form id="form1" runat="server">
Is it possible to tell in the code behind if the user hasn't done this i.e. they only did this:
<form id="form1">
Here the form has the id "form1" but in my case I don't know this. Code behind such as this is what I am looking for:
if(Page.HasForm)
{
}
You can only ever have one form tag with "runat=server" on it per .aspx page. All you have to do is to check to see if Page.Form is null or not. If it's null, then there's no form that has been marked to runat server.
if (Page.Form != null)
{
}
It's the runat="server" part that makes the .aspx page process an element and create a corresponding object on the server side. If a component is not running on the server, then it's not added to the page's control hierarchy.
var v = this.Form.TagName; //gets the name of the form that is maked as runat.
Of course if its not maked as runat then your code behind won't run anyway...
When you code in C# or Visual Basic in the code page, you will not have access to the object that do not have the runat=server option set.
You can easily access all the controls from a page using the me.controls page or something of the sort (I don't know the exact code but it's close to this) and check the type of the control to get the form.
Why do you need to know that? If a page does not have a runat=server form, it can't really be used as a server page.
You'd be able to access the form from the codebehind:
Response.Write(form1.Name);
Without the runat="server", you'd just get a compiler error.

asp.net button use javascript return function

I have an asp:button control and am using the "CommandName" and "CommandArgument" parameters in the .aspx file. The CommandName is found with <%# Eval("Name") %>, but the CommandArgument has to be found via a javascript function. However, I'm not quite sure how to do this inline. The function returns a number (integer), which is to be used as the value of the CommandArgument. Is it possible to do this?
Thanks
EDITED TO ADD CODE
I've added an example code (don't have access to the real code atm). However, basically, the CommandArgument should be the value returned by the function CalculateLength().
function CalculateLength(a,b) {
return a*b;
}
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName=<%# Eval("Name") %> CommandArgument= ??? //Should be result of CalculateLength(a,b).
I am not sure how you are going to get the javascript to work because the aspx code is running server side and building the output for your button. By the time the javascript runs the page code has already been built and the button's html and attached javascript as well.
Is there anyway to calculate the function server side and then just do:
CommandArgument="<%= CalculateLengthServerSide() %>"
You don't need to just use the data your binding to, you can call any server side function.
Edit: Try switching your label that stores the quantity to a textbox and making it read only so uses will not mess with it. After the button is clicked, you should be able to find the textbox control and read out the posted value.

ASP.Net PostbackURL doesn’t work if I put in Javascript Validation

I would like to share my problem with you in detail.
1) I have a textbox and a button in my page consider it as home.aspx
2) I have written the code like this:
<asp:Button id="btnSubmit" runat="server" Text="Submit" PostBackUrl="~\search.aspx"
OnClientClick="validate();" />
3) I have to check wheteher the textbox is null. If not null i want to redirect to search.aspx as given in the postbackurl.
4) Using java script i have validated;
function validate()
{
if(document.getElementById('txtCity').value!='')
{ alert('please enter the city to search'); returnn false;}
}
5) If the textbox is null. It alerts to enter the city. If not the page remains. It is not redirected to the search page.
I hope you can..
Kumar,
You will need to provide much more information then this.
A blind guess at what you are asking, is that you have a button on your page that causes validation. However, also on your page you have a linkbutton that should not cause validation, but just direct to the PostBackUrl.
You can accomplish this one of two ways:
1. Add a validation group to your button and all the controls it should validate.
2. On your LinkButton, add CausesValidation="false" to your declaration.
If these blind guesses are not helpful, please provide much more information.

Resources