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
Related
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());
I have problem with UpdatePanel (ASP.Net WebForms, .Net 4.0). Here is code:
<div class="container-fluid">
<form id="form1" runat="server">
<h2>Poruke</h2>
<div class="row">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel ID="msgListUpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div class="col-md-4">
<asp:ListBox ID="msgList" runat="server" OnSelectedIndexChanged="msgList_SelectedIndexChanged" AutoPostBack="true" ClientIDMode="AutoID"></asp:ListBox>
</div>
<div class="col-md-8">
<asp:ListBox ID="conversationList" runat="server" ClientIDMode="AutoID"></asp:ListBox>
<br class="divider" />
<p>
Odgovor: <span>
<asp:TextBox ID="replyTxtbox" runat="server"></asp:TextBox></span>
</p>
<asp:Button ID="sendBtn" runat="server" Text="PoĊĦalji" OnClick="sendBtn_Click" EnableViewState="false" ClientIDMode="AutoID" />
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="msgList" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</div>
and this is codebehind...
int userIdCookie = 0;
message selected = new message();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
if (!Page.IsPostBack)
{
if (Int32.TryParse(HttpContext.Current.User.Identity.Name, out userIdCookie))
{
message msg = new message();
var allMsg = msg.allMessagesFormatted().Distinct().ToList();
msgList.DataSource = allMsg;
msgList.DataBind();
}
}
else
{
// test only!
replyTxtbox.Text = msgList.SelectedIndex.ToString();
msgListUpdatePanel.Update();
}
}
protected void msgList_SelectedIndexChanged(object sender, EventArgs e)
{
message msg = new message();
var allMsg = msg.allMessagesFormatted().Distinct().ToList();
msgList.DataSource = allMsg;
IList<message> boundList = (IList<message>)msgList.DataSource;
selected = boundList[msgList.SelectedIndex];
var conversation = msg.allMessagesFormatted().FindAll(x => x.conversationGuid == selected.conversationGuid);
conversationList.DataSource = conversation;
conversationList.DataBind();
}
protected void sendBtn_Click(object sender, EventArgs e)
{
if(selected.recipientId != 0)
{
message newmsg = new message();
newmsg.senderId = userIdCookie;
newmsg.recipientId = selected.recipientId;
newmsg.subject = selected.subject;
newmsg.messageTxt = replyTxtbox.Text;
newmsg.conversationGuid = selected.conversationGuid;
newmsg.time = DateTime.Now;
newmsg.Add();
}
}
msgList gets populated fine but when i change selection, nothing happens - its SelectedIndex event never fires. If I set AutoPostBack="true" to this listbox, it reloads page (which is exactly what I am trying to avoid).
To sum up - when i click on item in ListBox inside UpdatePanel, nothing happens (event isn't fired). I want to avoid page reload when selected index changes. I've tried dozen of solutions (ClientID, AsyncPostBack, "regular" PostBack triggers and I guess i missed one simple detail and it's driving me mad.
Can anyone help?
edit - as #mason pointed out, problem was in overidden message.ToString() method that contained \r\n chars which caused problems in postback.
You will receive a JavaScript error in your browser's console.
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback
or callback argument. Event validation is enabled using in configuration or <%# Page
EnableEventValidation="true" %> in a page. For security purposes,
this feature verifies that arguments to postback or callback events
originate from the server control that originally rendered them. If
the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1 Uncaught
Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback
or callback argument. Event validation is enabled using in configuration or <%# Page
EnableEventValidation="true" %> in a page. For security purposes,
this feature verifies that arguments to postback or callback events
originate from the server control that originally rendered them. If
the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
You can see a simpler version if you use:
msgList.DataSource = new List<string>(){"A\r\n","B\r\n","C\r\n"};
When you watch it in the browser tab, you'll see POST request sent to the server, but on the server side the Page_Load method won't get hit at all.
The fix is either to not use \r\n characters in the data being used for the ListBox or to follow the directions to register it at ClientScriptManager.RegisterForEventValidation on MSDN.
I have a repeater with radiobuttons in it.
<script type="text/javascript">
$(document).ready(function ()
{
$("#test input:radio").attr("name", "yourGroupName");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="test">
<asp:Repeater runat="server" ID="rep" onitemdatabound="rep_ItemDataBound"
onitemcommand="rep_ItemCommand">
<ItemTemplate>
<asp:RadioButton ID="n" runat="server" Text='<%# Eval("name") %>' AccessKey='<%# Eval("id")%>' />
</ItemTemplate>
</asp:Repeater>
</div>
I am using the javascript at the top to fix the radiobutton bug in .net.
i bind a list to the repeater at page load, with a if (!Page.IsPostback) around it.
edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
rep.DataSource = z.Table.ToList();
rep.DataBind();
}
}
then i have a button, that when clicked should do something with the radio button that's been selected, this is the problem now:
foreach (RepeaterItem i in rep.Items)
{
RadioButton erb = i.FindControl("n") as RadioButton;
if (erb.Checked)
{
//do stuff
}
}
no matter which radiobutton i select, when i click the button and i debug the entire loop, every checkbox == false. i'm doing more stuff with the code but i've simplified it, because this is the biggest problem.
i have seen countless of topics about this issue and i have looked through them all but i still can't seem to get this to work.
Please try adding OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" on you radio button this will trigger post back on click of the button and you will be able to find the Checked one
I think this is all down to the sequence of events in ASP.NET .
Try putting your DataBind code in the Page_Init procedure, that way the state of the radiobuttons will be set by the time it reaches the Page_Load procedure.
I have the following markup / code block in the ASPX file.
The binding of the ddl is triggered after Page_Load event which is in the code behind file.
This results me not able to get the selected value of the dropdownlist if I were to use such flow.
However for some purpose I require it to work this way.
Any idea how I could get the dropdownlist selected value when a post back is being triggered (click of the button)?
Page URL: page.aspx?para1=0¶2=value
ASPX PAGE
<%
if (Convert.ToInt32(Request.QueryString["para1"]) == 0)
{
ddl.DataValueField = "value";
ddl.DataTextField = "text";
ddl.DataSource = ds; //ds is valid, exact code not shown
ddl.DataBind();
} else {
//write in this area
Response.Write("Not 0");
}
%>
<form runat="server" id="user_form" class="form-horizontal">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
<%-- this button will call btnSave_Click to get the ddl's value--%>
<asp:Button runat="server" ID="btn" Text="Button" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do my stuff
}
}
protected void btn_Click(object sender, EventArgs e)
{
int intValue = Convert.ToInt32(ddl.SelectedValue);
//do my stuff
}
The ASPX Page code block will run after Page_Load / page's lifecycle, then will determine what to do base on the url parameters.
Thanks in advance!
You could always throw in a hidden object and use jquery to copy the value to the hidden value based on a certain action without a postback and would do it client side like it sounds like you want it to do
hi I have one parent page which opens a pop up window, and user makes some changes on child pop up page then clicks a save button.
When the user clicks the save button, I want to doPostBack to the parent page so that the changes made in the pop up window can be seen in parent window.
Question : How can I achive the above scenario?
I want to write the script code in aspx.cs file, I tried
string script = "";
script = "<script>window.opener.__doPostBack('UpdatePanel1', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
but this did not do anything, no errors just nothing.
I am new to JavaScript, need help with all steps.
The parent page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div>
<asp:Literal runat="server" ID="ChildWindowResult" />
</div>
<hr />
<input type="button" value="Open Dialog" onclick="window.open('MyDialog.aspx', 'Dialog');" />
<asp:Button ID="HiddenButtonForChildPostback" runat="server"
OnClick="OnChildPostbackOccured" style="display: none;" />
<asp:HiddenField runat="server" ID="PopupWindowResult"/>
</ContentTemplate>
</asp:UpdatePanel>
The MyDialog page:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function postData() {
var resultField = $("input[type='hidden'][id$='PopupWindowResult']", window.opener.document);
var parentPosDataButton = $("[id$='HiddenButtonForChildPostback']", window.opener.document);
resultField.val($("#<%= SomeValueHiddenField.ClientID %>").val());
parentPosDataButton.click();
}
</script>
<asp:TextBox runat="server" ID="SomeValueHiddenField" />
<asp:Button runat="server" OnClick="PostData" Text="Click Me" />
protected void PostData(object sender, EventArgs e)
{
SomeValueHiddenField.Value = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(), "PostData", "postData();", true);
}
But I believe that it would be much better to utilize here some pop-up controls like PopUpExtender from the AjaxControlToolkit library or dialog from the jQuery-UI.
You probably need to use ClientID:
string script = "";
script = "<script>window.opener.__doPostBack('" + UpdatePanel1.ClientID + "', '')</script>";
ScriptManager.RegisterClientScriptBlock(Literal1, typeof(Literal), "yenile", script, true);
The last parameter is to whether include script tag or not
So, if you do
RegisterClientScriptBlock(page,type, "<script>foo();</script>", true);
You will end up with:
"<script><script>foo();</script></script>"
So, change your last parameter to false, or better yet, remove the tags in the string
Review the following suggested solution:
http://livshitz.wordpress.com/2011/06/12/use-popup-to-postbackupdate-its-parentopener-without-losing-viewstate-values-and-close/#more-16