I am trying to create a search bar for my ASP.NET pages that will be included in the master so it will be shown on all pages. Entering search text and hitting search will send you to results.aspx, which then retrieves the value of the text from the master page search box and displays data from the database in a grid view. Searching from my home page works fine, but I want the user to be able to enter a new search text while on the results page and have the page reload with the new data in the grid view.
Here is the code on results.aspx page load
if (PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)PreviousPage.Master.FindControl("txtSearchMaster");
if (SourceTextBox != null)
{
txtSearch.Text = SourceTextBox.Text;
}
}
Code on master page
<div id="search">
<asp:HyperLink ID="linkAddFile" runat="server" BorderStyle="None" NavigateUrl="~/Default.aspx" Width="150px" >Add File</asp:HyperLink>
<asp:TextBox ID="txtSearchMaster" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" PostBackUrl="~/results.aspx" />
</div>
The issue is once I get to the results page and try to do a new search from there, my conditional (PreviousPage != null) says that it is null.
Don't get the search values from the previous page via PreviousPage property.
Instead, when the user performs a search, grab the value from the search textbox and pass the value to the results page. Example:
master page
<div id="search">
<asp:TextBox ID="txtSearchMaster" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
Master Code behind
protected void btnSearch_Click(object sender, EventArgs e)
{
var searchText = Server.UrlEncode(txtSearchMaster.Text); // URL encode in case of special characters
Response.Redirect("~/Results.aspx?srch="+searchText);
}
Results page code behind
protected void Page_Load(object sender, EventArgs e)
{
if(!String.IsNullOrEmpty(Request.QueryString["srch"])
{
//perform search and display results
}
}
I think you should not get the search values from the previous page via PreviousPage property.
Instead, you can also do this:
TextBox mastertxt = (TextBox)Master.FindControl("txtSearchMaster");
Response.Redirect("~/YourResultPage.aspx?search="+mastertxt.Text.ToString());
Related
I have a method being used on a button to redirect to a different page. There are several variables that are inserted into the URL to help navigate to what the user wants to see. It works well, except for the fact that the variables do not show up in the address bar.
Upon button click and redirect to the next page the url looks like: /Beta.aspx/?year=&track=&event=&car=27&session
How can I get my variables to show up in the address bar? Below is the code being used for the button click.
protected void btnConfirm_Click(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx/?year={0}&track={1}&event={2}&car=27&session{3}",hidYear.Value, hidTrack.Value, hidEvent.Value, hidSession.Value);
Response.Redirect(url);
}
Button Setup
<telerik:RadImageButton ID="RadImageButton2" runat="server" Skin="Material" Text="27" OnClick="btnConfirm_Click">
</telerik:RadImageButton>
Form Tag
<form id="form1" runat="server" class="SmallFont">
Hidden Fields
<asp:HiddenField runat="server" ID="hidYear" />
<asp:HiddenField runat="server" ID="hidTrack" />
<asp:HiddenField runat="server" ID="hidEvent" />
<asp:HiddenField runat="server" ID="hidSession" />
When RadImageButton2 is clicked, the page is posted back to the server for processing. This process is called ASP.NET postback mechanism and IsPostback is normally used on page_load event to detect if the page is getting generated due to postback requested by a control on the page, or if the page is getting loaded for the first time. This is important for the case when values of the controls are set programmatically and should not be overwritten when page was posted back.
See this snippet:
protected void Page_Load(object sender, EventArgs e)
{
hidYear.Value = "";
hidTrack.Value = "";
hidEvent.Value = "";
hidSession.Value = "";
}
protected void Init_Click(object sender, EventArgs e)
{
hidYear.Value = "2020";
hidTrack.Value = "1";
hidEvent.Value = "2";
hidSession.Value = "0123456789";
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
string url = string.Format("Beta.aspx/?year={0}&track={1}&event={2}&car=27&session{3}",
hidYear.Value, hidTrack.Value, hidEvent.Value, hidSession.Value);
Response.Redirect(url);
}
It all will run well, but values on the redirect will be always "" because Page_Load() is called with every postback. However, with the following little change the values on redirect will be not changed and populated to the state before form submit:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
hidYear.Value = "";
hidTrack.Value = "";
hidEvent.Value = "";
hidSession.Value = "";
}
}
Note, actual values of controls can be found by looking at the source of the page
Bottom line here: hidden fields should have values when looking at the source before clicking on RadImageButton2 and Page_Load() should not call any code that changes those values, or should check for if (!IsPostBack).
P.S.
Simple redirect does not required server code and can be done with client script, example:
<script type="text/javascript">
function PageRedirect() {
window.location.href = "Beta.aspx/?year="
+ document.getElementById('<%=hidYear.ClientID%>').value
+ "&track=" + document.getElementById('<%=hidTrack.ClientID%>').value
+ "&event=" + document.getElementById('<%=hidEvent.ClientID%>').value
+ "&car=27&session" + document.getElementById('<%=hidSession.ClientID%>').value;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Client Redirect"
OnClientClick="PageRedirect();return false;" />
You're saying that it does work. That means that the variables are being passed.
There is a chance that the solution is really, really simple.
Variables don't show up in the address bar until you click on it. Try clicking on the URL in your address bar, it will select the URL and the variables will show. If not, only then it has to do something with the code.
Ahh, there's the mistake Bro. there isn't any value for these hidden controls
<asp:HiddenField runat="server" ID="hidYear" />
<asp:HiddenField runat="server" ID="hidTrack" />
<asp:HiddenField runat="server" ID="hidEvent" />
<asp:HiddenField runat="server" ID="hidSession" />
either you can add value in the ASPX page as
<asp:HiddenField runat="server" ID="hidYear" Value="1234"/>
<asp:HiddenField runat="server" ID="hidTrack" Value="4321" />
<asp:HiddenField runat="server" ID="hidEvent" Value="1234" />
<asp:HiddenField runat="server" ID="hidSession" Value="2405"/>
or as mentioned by user https://stackoverflow.com/users/2316116/user2316116 you can use
hidYear.Value = "2020";
hidTrack.Value = "1";
hidEvent.Value = "2";
hidSession.Value = "0123456789";
the reason the value is not being displayed in the URL is simply that there isn't a value that can be displayed.
make sure to check for empty values if you're taking inputs from the user in future applications. 😀
You should not have '/' between 'beta.aspx' and '?'. Try removing that extra slash and see if that resolves your issue.
I have a simple page with Jquery datepicker, UpdateProgress, and GridView inside of UpdatePanel.
Here is a fragment from the page:
...
Select From Date: <input type="text" id="datepickerfrom" name="datepickerfrom"/>
Select To Date: <input type="text" id="datepickerto" name="datepickerto"/>
<asp:Button ID="btnGetData" runat="server" OnClick="BtnGetData_Click" Text="Get Error List" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
...MyGrid...
</ContentTemplate>
</asp:UpdatePanel>
...
This is the code behind method invoked when clicking on the button:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = HttpUtility.HtmlEncode(Request.Form["datepickerfrom"]);
string dateTo = HttpUtility.HtmlEncode(Request.Form["datepickerto"]);
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
When I first load the page and click on one of the Date's text boxes, jQuery datepicker is poped up. When I refresh the page, it pops up as well.
However, after clicking on the button and populating the GridView with the data, it is not displayed anymore.
What can be the reason?
Your tag is
<input type="text" id="datepickerfrom" name="datepickerfrom"/>
This is really the regular html tag. Microsoft ASP.NET does NOT keep the state (ie in ViewState) of regular html tag. After postback, the page life cycle effectively creates a new instance of Page (System.Web.UI.Page) object before sending response back to browser as html.
On the other hand, once you change to
<asp:TextBox ID="datepickerfrom" runat="server" />
You will see it in postback. Also the way you capture those 2 dates in code behind is obsolete (only seen in ASP 1.1).
The namespace for your text tag is
System.Web.UI.HtmlControls.HtmlInputText and the namespace for the server tag is System.Web.UI.WebControls.TextBox. They belong to different namespaces. Any controls in the HtmlControls are for legacy purpose.
You may change to asp:TextBox and access them from code behind as follows:
protected void BtnGetData_Click(object sender, EventArgs e)
{
string dateFrom = datepickerfrom.Text; // -- updated
string dateTo = datepickerto.Text; // -- updated
InputData data = new InputData(dateFrom, dateTo);
Session["inputData"] = data;
gvErrorLog.PageIndex = 0;
LoadLogErrorData(data);
}
If you insist on your tags, you can add a hidden variable and update those hidden variable on change event of your textboxes.
I assume your textboxes are set up like the following
$(function () {
$("#<%=datepickerfrom.ClientID%>").datepicker();
$("#<%=datepickerto.ClientID%>").datepicker();
});
I finally found the answer to my problem here:
http://www.jquerybyexample.net/2010/08/jquery-datepicker-does-not-work-after.html
I have a web form as
<asp:TextBox ID="txtname" runat="server" Text="Post on Next Page"/>
<asp:Button ID="btn1" runat="server" PostBackUrl="~/Page2.aspx" Text="Post on next page" />
Now on Page2.aspx the code-behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(PreviousPage!=null && PreviousPage.IsCrossPagePostBack)
{
TextBox txt1 = (TextBox)PreviousPage.FindControl("txtname");
label1.Text = "Value: " + txt1.Text;
}
}
I end up getting the error object reference not set to instance of an object for txt1
Where label1 is a label used to display the output. However, the value is not displayed.
What step am i missing?
Try this
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
//get the content place holder from master page of your previous page where your controls are placed
//In this code the txtname textbox is placed inside ContentPlaceHolderID="MainContent"
var cp =PreviousPage.Master.FindControl("MainContent") as ContentPlaceHolder;
//find the textbox inside content place holder from previous page
TextBox txt1 = cp.FindControl("txtname") as TextBox;
label1.Text = "Value: " + txt1.Text;
}
Are you sure that PostBackURL is valid on a Textbox? Normally this attribute is attached to something that submits, such as a Button or LinkButton, eg:
<form runat="server">
Name:<asp:textbox id="TextBox1" runat=Server />
<asp:button id="Button1" Text="Submit"
PostBackUrl="demo_postbackurl.aspx" runat="Server" />
</form>
Edit: Aha! - you do use a button.
Your code looks OK to me.
If the TextBox is within another control FindControl might not find it - if (for example) it's within a Panel you would need to do something like
TextBox txt1 = (TextBox)PreviousPage.MyPanel.FindControl("txtname");
If it's not within another control then I'm afraid I don't know.
CODE BEHIND:
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlLanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload the page for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
//Server.Transfer(Request.Path);
}
protected void OKButton_Click(object sender, EventArgs e)
{
Server.Transfer(Request.Path);
}
ASPX PAGE:
<asp:DropDownList ID="ddlLanguage" class="langpnl" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
<asp:ListItem Value="en-US">Eng</asp:ListItem>
<asp:ListItem Value="es-ES">Esp</asp:ListItem>
</asp:DropDownList>
<ajaxToolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="testhidden"
PopupControlID="pnlPopup" OkControlID="OKButton" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" Style="display: none">
All content may not be in Spanish.
<asp:Button ID="OKButton" runat="server" Text="OK" OnClick="OKButton_Click" />
</asp:Panel>
<asp:HiddenField ID="testhidden" runat="server" />
I am trying to set the language as per the selection in the Dropdown box. But if the user selects spanish I want to display a popup modal with a msg & once the button OK is pressed I want to postback the whole page.
Currently I am able to display the popup but the page never refreshed so the language still doesn't change. In the code behind if I remove the server.transfer from the OK button and put it in the SelectIndexChange then the page postback is working but there is no popup masg .I think the page gets postback after the popup executes so it never gets displayed...please need some help I am breaking my head since last 3 days.
Define another button in that panel... and do whatever you want in his onclick event. So you will have a postback.
The OKButton click event... OKButton_Click will not fire as long as you assigned him in you modalpopup...
if (ddlLanguage.SelectedValue == "es-ES")
{
mdlPopup.Show();
}
else
{
Server.Transfer(Request.Path);
}
& removed the OK button from Modalpopup..finally got to see what I was Expecting..
I have the following code in my aspx page:
<asp:Button id="display_button" runat="server" Text="Display" OnClick="Button1_Click" />
<asp:Button id="edit_button" runat="server" Text="Edit" OnClick="Button2_Click" />
<asp:Button id="save_button" runat="server" Text="Save" OnClick="Button3_Click" Visible="false" />
<asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View id="View1" runat="server">
<asp:FormView id="view_program" runat="server">
<ItemTemplate>
<%# Eval("status").ToString().Trim() %>
</ItemTemplate>
</asp:FormView>
</asp:View>
<asp:View id="View2" runat="server">
<asp:FormView id="edit_program" runat="server">
<ItemTemplate>
<asp:DropDownList id="p_status" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
</asp:View>
</asp:MultiView>
and the following functions attached to the buttons in the code-behind page:
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
save_button.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
var status = p_status.SelectedValue;
Label1.Text = status;
//save_button.Visible = false;
//MultiView1.SetActiveView(View1);
}
The idea being, that there are two views, the first displays the information, if the user wants to edit the information, they click button 2 which changes the view to the edit mode, which has the controls (drop downs, text fields, etc). It also makes the 'save' button appear.
What I am trying to make happen is, when the save button is clicked, it will grab all of the values from the various fields, update the object and then update the database. Then it would flip back to view1 with the updated info.
Problem is, as you can see in void Button3_Click, I try grab the values from the control, p_status, but it only gets the original value. example, the menu has three values, 'Green', 'Yellow', and 'Red'. Green is the default value and is selected when view2 is displayed. However, if I select Yellow or Red, and click save, rather than the label being updated to display one of those two values, it always displays Green.
Any ideas?
edit: page load function per request below
protected void Page_Load(object sender, EventArgs e)
{
try
{
Person myPerson = new Person(userid);
TestProgram myProgram = new TestProgram(id);
List<TestProgram> program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
edit_program.DataSource = program;
edit_program.DataBind();
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
p_status.Items.Add(new ListItem("Green", "Green"));
p_status.Items.Add(new ListItem("Yellow", "Yellow"));
p_status.Items.Add(new ListItem("Red", "Red"));
//myProgram.Status = "Red";
p_status.SelectedValue = myProgram.Status;
}
catch (Exception ex)
{
Response.Write(ex);
Label1.Text = ex.ToString();
}
}
Whoops...missed a little someting.. my
bad
when asp.net is not behaving as expected this is your best friend: MSDN: ASP.NET PAGE LIFECYLE
Upon Further Review...
there are a couple of problems here. your drop down list control with an id of "p_status" is contained inside a multiview (I forgot about what that meant...) you need to move the code to populate p_status into pre-render after checking to see if Multiveiw1.ActiveView = View2. Since it will always be a post back you need to bind values late in the page cycle