dynamically filled div controls gets blank when page gets postback - jquery-ui

I am working on asp.net, C# web application.
Working on my main page in application, where all the codes are synchronize and works well.
Now, I need to change some of the functionality using ajax JQuery Asyn. calls. In my case it works for me. everything is fine.
Now my page is having asp.net AjaX Timer Control which gets fire at every one minute. This is one of the functionality which is need to be there and not able to change using jQuery.
Now, when my timer event (Tick) fires at every one minute, my dynamically filled div ( html() of ajax jquery) gets blank when page gets postback.
i.e. consider my page having div with id = div1, and this gets filled with ajax jQuery call which returns me html of remote page, so the content of that is totally dynamic.
When page gets fired, that div is blank..
How can I keep my div's to be as it is when my page gets post back?
(think this is possible as Gmail works on the same thing, how they mantain?)
Please let me know if require more details if not clear.
Below is the image with ajax call.
now, when pages gets postback, it is something like below....
it is not possible for me to give complex code here, how ever i give a sample code here by.
<asp:ScriptManager ID="Scriptmanager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick" Enabled="true">
</asp:Timer>
<div>
<asp:Button Text="text" runat="server" OnClientClick="callfun();return false;" />
</div>
<asp:Button Text="text" runat="server" ID="btn" OnClick="btn_Click" />
<div id="div1">
</div>
<script>
});
function callfun() {
$("#div1").html("test me, test me");
}
</script>
code behind.....
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("postback");
}
protected void Timer1_Tick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
}

Please use pageLoad(). It gets fired after each update panel refresh.
var cached_html;
$(document).ready(function() {
cached_html = "html returned from an ajax call"
$("#div1").html(cached_html);
});
function pageLoad() {
$("#div1").html(cached_html);
//if this doesn't work, you need to make ajax call each time the refresh happens
}
And forget gmail for now. They do not have a Sys is undefined :)

Related

UWP WebView control doesn't refresh when asked if page request method was POST

The UWP WebView control has a Refresh() method that works fine for most pages, but calling the method directly after the WebView has been navigated somewhere by POST (e.g. a form submission inside the WebView itself) raises the NavigationStarted event, but never actually performs any refresh.
Here's some minimised XAML that demonstrates the issue:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Name="Refresh" Click="Refresh_Click" Content="Refresh" />
<WebView Grid.Row="1" Name="BrowserView" />
</Grid>
</Page>
Here's the relevant code-behind:
namespace App1
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
BrowserView.NavigationCompleted += BrowserView_NavigationCompleted;
BrowserView.NavigationStarting += BrowserView_NavigationStarting;
BrowserView.Navigate(new Uri("http://localhost/test.php"));
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
BrowserView.Refresh();
}
private void BrowserView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// Always called on first load and when refreshed (even for POST results)
Debug.WriteLine($"Navigation starting for URI {args.Uri}");
}
private void BrowserView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// Not called when a POST result is being refreshed
Debug.WriteLine($"Navigation completed");
}
}
}
As a test, I've created and hosted a very small PHP page with the following content and hosted it at http://localhost/test.php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="POST">
<p>Page loaded at <?php echo date('H:i:s') . (!empty($_POST['in']) ? ' with text "'.htmlspecialchars($_POST['in']).'"' : '') ?></p>
<input type="text" name="in" />
<input type="submit" />
</form>
</body>
</html>
Once I point my WebView at this page I can refresh the page on the initial load just fine, but after submitting the form, Refresh() raises the NavigationStarting event but does not navigate the page at all (as indicated by the timestamp on the test PHP result not changing) and never raises a corresponding NavigationCompleted event.
When the same page is visited in Edge, the user is shown this warning when attempting to refresh a POST result:
Choosing Retry resubmits the POST data to the server, and choosing Cancel behaves similarly to what I'm seeing (doing nothing at all). This dialog is obviously not emulated in any way by the UWP WebView control.
Since my actual application shows users a refresh button, I need the button to do something regardless of whether or not they've recently submitted a form, or alternatively I need to disable the refresh button so it's not confusing to users when the button does nothing.
Right now the only solution I have (which astonishingly seems to work, but is really nasty) is to call GoBack(), then in the NavigationCompleted event handler immediately call GoForward().
I could settle for an option that allows me to detect this condition (something like WebView.CanRefresh so that I could disable my Refresh button), or worst case scenario some kind of result/exception that allows me to communicate to the user what has (not) happened and why.
If I understand your question correctly, you want to refresh the page after form has been submitted.
If so, you could check if the form has been submitted in php handler. Please check this thread: Checking if form has been submitted - PHP. Then, in the php handler, you could call the javascript method to refresh the page like window.location.reload().

Repeater.Items only populates in Button click event when I DataBind in that event, but all textbox inputs are empty

I have a repeater that is databound to a SqlDataSource
<asp:Repeater runat="server" ID="Repeater" DataSourceID="SqlDataSource">
<ItemTemplate>
<asp:HiddenField runat="server" Value='<%# Eval("Code") %>' ID="Code" />
<asp:TextBox ID="NumberNeeded" runat="server" Text='<%# Eval("Needed") %>' /><br />
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" ID="submit" Text="submit" OnClick="submit_Click" />
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="rtvFiltered" SelectCommandType="StoredProcedure">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
I want to iterate over the repeater and get the value in NumberNeeded in submit_Click
protected void submit_Click(object sender, EventArgs e)
{
this.Repeater.DataBind(); //comment this guy and this.Repeater.Items has no items
foreach (RepeaterItem item in this.Repeater.Items)
{
String code = ((HiddenField)item.FindControl("JournalCode")).Value;
// below fails because "NumberNeeded" control doesn't have the Text input by the user.
int numNeeded = Int32.Parse(((TextBox)item.FindControl("NumberNeeded")).Text);
// Doing other stuff with numNeeded
}
}
The repeater displays its items perfectly on the page, but when I click the submit button, this.Repeater.Items is empty (unless I call this.Repeater.DataBind() in that method).
I've tried explicitly data binding Repeater in Page_Load and Page_Init within and outside of a !Page.IsPostBack check, and everytime I either get no Items, or no Text value.
I have gotten an almost identical setup to work in the past, on a page without a master page. I've also noticed that this.Master.EnableViewState is false in the submit_Click method, no matter if I set it to true in Page_Init or Page_Load. this.EnableViewState is true.
As you state, you shouldn't need to call DataBind() in your code behind, so the problem may be with the data retrieval. Does your stored procedure take any parameters? Have you tried adding CancelSelectOnNullParameter="false" to your SqlDataSource?
It was the EnableViewState setting on the master page.
In the Page_Load method of the master page this.EnableViewState was getting set to false. I changed it to Page.EnableViewState and everything worked.
this.EnableViewState = Page.EnableViewState; // add to Master page Page_Load method
do'h

ASP.NET : Textbox OnTextChanged MVC refresh whole page

I'm having a trouble while devolping my .net application.
I'm using the event OnTextChanged on a textbox to change the content in another Textbox, the first textbox has AutoPostBack="true", but when i write in it and click in another part, the page refreshes completely.
here is my ascx code:
<form id="Form1" runat="server">
Change text
<asp:TextBox id="txt1" runat="server" ontextchanged="ejemplo" autopostback="true"/>
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
and the script in the same ascx page:
<script runat="server">
protected void ejemplo(object sender, EventArgs e)
{
lbl1.Text = "Changed";
}
</script>
I'm using MVC4,
Thanks for your answers.
EDIT:
here is a video of what is really happening:
http://remainedesign.com/video/asd.html
Life cycle of MVC and webforms both are different.
MVC is not about server controls.... viewstate... no page life cycle events in web form...
What is the 'page lifecycle' of an ASP.NET MVC page, compared to ASP.NET WebForms?
hope this helps..
Now coming to your point.
if you want to display something in the Textbox2 while entering a Value into the Textbox1 you have to use client side script, see example below
javascript
<script type="text/javascript" language="javascript">
function textCounter(field, field2, maxlimit) {
var countfield = document.getElementById(field2);
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
return false;
} else {
countfield.value = maxlimit - field.value.length;
}
}
</script>
Your Html page
<%using (Html.BeginForm("Index", "Account", FormMethod.Post)) // here index is a ActionName, Account is a controller name
{%>
<input type="text" id="textbox1" name="Message" onkeyup="textCounter(this,'textbox2',208)"/>
<input disabled maxlength="3" size="3" value="208" id="textbox2" /></label>
<input type="submit" value="Send" />
<%}%>
Here
textCounter() function on keyup event in textbox1 will display value in textbox2,
submit button will submit form which call action "index" on controller "Account",see below how action act
public class AccountController : Controller
{
[HttpPost]
public ActionResult index(FormCollection result)
{
string TextBoxValue=result["Message"];
return view("yourviewname");
}
}
please note,above example is solely for MVC project
i hope this example may help you..
the first textbox has AutoPostBack="true", but when i write in it and
click in another part, the page refreshes completely
That is exactly what AutoPostBack is for. If you click on another part, that's when you lose focus on the textbox and it will trigger a postback. If you need more proof then read this from MSDN:
Gets or sets a value that indicates whether an automatic postback to
the server occurs when the TextBox control loses focus.

JQuery UI button submitting entire content problem in IE 6.0

I have the same problem as posted here
I have a <button> element that triggers "A potentially dangerous request.form value..." error in asp.net MVC. For instance:
<button type="submit" name="logon" value="ok">Confirm</button>
<button type="submit" name="cancel" value="ok">Cancel</button>
And this javascript (with jquery UI 1.8.5)
<script type="text/javascript">
$(document).ready(function() {
$("button").button();
});
</script>
The issue is that I can't remove the name property (as the given solution in the link I posted) because I capture which button is pressed in the controller side this way:
public ActionResult Logon(FormCollection form, string logon, string cancel)
{
if (!string.IsNullOrEmpty(logon))
{
DoLogon();
}
if (!string.IsNullOrEmpty(cancel))
{
Cancel();
}
//etc
}
Is there any workaround for this? Thanks. Note that I don't have this problem in IE8 or firefox.
Have you seen this?
Cause
The .NET framework is throwing up an error because it detected something
in the entered text which looks like an HTML statement. The text doesn't
need to contain valid HTML, just anything with opening and closing
angled brackets ("<...>").
The solution proposed there is to disable the request validation on the server-side:
<pages validateRequest="false" />
Be sure to read through the warnings and explanations as well.

AJAX behaving differently for Submit button vs. this.form.submit?

I'm trying to auto-save a selection in a dropdown (ASP.NET, MVC, VB), but it's not behaving as expected. Here's the dummy action in the controller:
<AcceptVerbs(HttpVerbs.Post)> _
Function TestAction(ByVal id As Integer) As ActionResult
Return Content(id)
End Function
and the HTML:
<script type="text/javascript" src='<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>'></script>
<script type="text/javascript" src='<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>'></script>
<% Using Ajax.BeginForm("TestAction", New AjaxOptions With {.UpdateTargetId = "test"})%>
<%=Html.Hidden("id", 123)%>
<%=Html.DropDownList("actions", Nothing, New With {.onchange = "this.form.submit();"})%>
<input type="submit" value="Submit" />
<span id="test"></span>
<% End Using%>
The Submit button works as expected - the span is populated with "123". The dropdown on the other hand opens a new page with nothing but "123" on it. Why "this.form.submit()" not doing the same thing as the Submit button? Is there a different call I should make to emulate the Submit button?
this.form.submit does not run the form.onsubmit event. Pressing the submit button, on the other hand, does. That, combined with the HTML that Ajax.BeginForm generates, explains why the two behave differently. As for how to make your event do the same thing as pressing the submit button, look at the HTML in the linked article:
Sys.Mvc.AsyncForm.handleSubmit(
this,
new Sys.UI.DomEvent(event),
{
insertionMode: Sys.Mvc.InsertionMode.replace,
updateTargetId: 'test'
});
I know this is old, but there is a new (and better) way to do this.
Instead of doing using javascript, use jQuery. Just had this issue and it worked great.
this.form.submit() <---- Javascript
$("form").submit() <---- jQuery

Resources