edit inner html div - asp.net

i am a beginner
function PopupUserRegist() {
result = $.ajax({ url: "Default.aspx?cmd=Setting",
async: false ,
complete: function () {
// unblock when remote call returns
}
}).responseText; ;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request["cmd"] == "Setting")
{
div.InnerText = "test"; //This does not change inner text
}
}
protected void Button2_Click(object sender, EventArgs e)
{
div.InnerText = "test";//This change inner text
}
when call PopupUserRegist(); does not change?

You've got confused about the flow of control with ASP.NET.
Page_Load() occurs on the server side at page generation time and can change the data that is about to be sent back in the HTML page to the browser.
When you call the ASPX again through ajax() from JavaScript, the codebehind can't directly touch the page content, because that's already sitting over on the browser. If you want to change the data in the page, you'll have to have the ASPX return a plain value to the JavaScript code in the responseText:
$('#myDiv').text(
$.ajax({
url: 'Default.aspx?cmd=Setting',
async: false
}).responseText
);
or, better, avoiding the unpleasant use of synchronous xmlhttprequest:
$.get('Default.aspx?cmd=Setting', function(result) {
$('#myDiv').text(result);
});
If you really want to blur the line between code that runs on the client and server sides, look at using runat="server", click events, postbacks and viewstates.

Check if the condition is met.

Related

Would a Page Method finish execution even after user leaves page?

I was wondering. I tried googling for answers but they don't give me answers. Thanks.
Yes, an ASP.NET AJAX Page Method will continue execution after a user leaves a page, but the result (if any) will not come back to the page, since the page where the request was initiated is now gone.
For example:
Code-behind on Default.aspx page:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetHelloWorld()
{
Thread.Sleep(20000);
return "Hello World";
}
protected void ButtonContactRedirect_OnClick(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
}
Markup on Default.aspx page:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetHelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
});
</script>
<asp:Button runat="server" ID="ButtonContactRedirect" Text="Go to Contacts Page" OnClick="ButtonContactRedirect_OnClick"/>
So we have a button on Default.aspx that will redirect to another page (Contacts.aspx) when the user clicks it. Meanwhile, when Default.aspx is loaded, there is an AJAX call to the page method that sleeps for 20 seconds before returning the string Hello World.
If you put a break point on the following line:
return "Hello World";
When you run the program and the page loads, if you do not click the button for 20 seconds then the AJAX success callback will fire and an alert will show the string object returned. If you press the button before the 20 second sleep finishes, then the Redirect() will happen and the Contacts.aspx page will load, but the break point will be hit once the sleep finishes; however the returned Hello World string will be lost, because the AJAX context was tied to the Default.aspx page and not the Contacts.aspx page, which is now gone.

edit inner html div [duplicate]

i am a beginner
function PopupUserRegist() {
result = $.ajax({ url: "Default.aspx?cmd=Setting",
async: false ,
complete: function () {
// unblock when remote call returns
}
}).responseText; ;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request["cmd"] == "Setting")
{
div.InnerText = "test"; //This does not change inner text
}
}
protected void Button2_Click(object sender, EventArgs e)
{
div.InnerText = "test";//This change inner text
}
when call PopupUserRegist(); does not change?
You've got confused about the flow of control with ASP.NET.
Page_Load() occurs on the server side at page generation time and can change the data that is about to be sent back in the HTML page to the browser.
When you call the ASPX again through ajax() from JavaScript, the codebehind can't directly touch the page content, because that's already sitting over on the browser. If you want to change the data in the page, you'll have to have the ASPX return a plain value to the JavaScript code in the responseText:
$('#myDiv').text(
$.ajax({
url: 'Default.aspx?cmd=Setting',
async: false
}).responseText
);
or, better, avoiding the unpleasant use of synchronous xmlhttprequest:
$.get('Default.aspx?cmd=Setting', function(result) {
$('#myDiv').text(result);
});
If you really want to blur the line between code that runs on the client and server sides, look at using runat="server", click events, postbacks and viewstates.
Check if the condition is met.

ajax with page method

I have a gridview inside an updatepanel and I have a javascript that calls a page method using jquery. I'd like the page method to refresh the gridview based on the parameter it receives from the ajax call.
So far, I have the following:
1) in the javascript, there's a function that calls the page method:
function GetNewDate(thedateitem) {
DateString = (valid json date format that works)
$.ajax({
type: "POST",
url: "./CallHistory.aspx/ResetDate",
contentType: "application/json; charset=utf-8",
data: DateString,
dataType: "json",
success: successFn,
error: errorFn
})
};
2) In the aspx page I have:
<asp:UpdatePanel ID="MyPanel" runat="server">
<ContentTemplate>
<asp:GridView ID="MyGrid">
3) In the code behind:
public partial class Pages_CallHistory : System.Web.UI.Page
{
List<ViewCallHistoryModel> TheCallHistory;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TheDate = new DateTime(2011, 1, 13);
LoadCallHistory(TheDate);
MyGrid.Datasource = TheCallHistory;
MyGrid.Databind;
}
}
protected void LoadCallHistory(DateTime TheDate)
{
linq query that fills the variable TheCallHistory
}
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
var test = new Pages_CallHistory();
var test2 = test.LoadCallHistory(TheNewDate.Date);
//test2 loads fine
test.GridCallHistory.DataSource = test2;
//this is not underlined but bugs at runtime
//Object reference not set to an instance of an object.
test.GridCallHistory.DataBind();
test.MyPanel.Update();
//this is not underlined but doesn't get executed because
//because it stops at the line above
//I'd like to update the content of
//the gridview on the page with the updated gridview.
}
What I'd like to do in the page method is 1) call LoadCallHistory with the new date parameter and 2) tell the gridview MyGrid to rebind with the new data that's in TheCallHistory.
I'm struggling with this page method; it's not working and I'm stuck. How is this done?
ok so the solution is to use _doPostBack in javascript:
__doPostBack('MyPanel', DateString);
The page method is for sending and receiving data only, not for doing postbacks on updatepanels.
Take a look at my answer to this related question here. In short, you create a new instance of the grid and capture its output manually.

Anchor tag validation

I am trying to make an anchor tag cause both client and server validation. I have this code for now:
$(document).ready(function () {
$('div#imgEmailVerifyLoader').hide();
$('a#btn_SubmitContactMessage').click(function ()
{
if (Page_ClientValidate()) // this will trigger all validators on page
{
$('div#imgEmailVerifyLoader').show('slow');
window.Form_OnMasterPage.submit();
return true;
}
else
{
return false;
}
});
});
<a id="btn_SubmitContactMessage" href="Contact.aspx" onclick="Validate();" runat="server">SUBMIT</a>
This performs client validation properly and shows the error message. I have validation controls for each of the textboxes on the page. I also added a server click event handler in code behind for this:
btn_SubmitContactMessage.ServerClick +=new EventHandler(btn_SubmitContactMessage_ServerClick);
}
protected void btn_SubmitContactMessage_ServerClick(object sender, EventArgs e)
{
if (!Page.IsValid)
{
RequiredFieldValidator4.ErrorMessage = "show";
return;
}
}
But when I try to test it by turning off javascript the link(submit) does not postback. Why is that happening?
Now, how do I make sure that validation is being done on the server side to after postback.
I would imagine it's because of the 'onclick=validate()'. Instead of doing that you should register that event inside of '$(document).ready(function ()' like you've got your other JavaScript. That way if JavaScript is not available the form is submitted normally and your server side validation kicks in.

How do I override page load lifecycle in ASP.NET to prevent ASPX form from loading?

I need to test a condition in several ASPX code-behind files and, in some cases, would like to completely bypass the normal page load process so that the corresponding ASPX page is not loaded. Intead, I'd like to send a custom response to the browser that's written from a code-behind method.
Does anyone know where to start- what method(s) in the page lifecycle to override and the best technique to ensure that my custom Response.Write is sent to the browser while the normal ASPX page content is suppressed?
Thanks.
Probably the easiest way to do it - use Page_Load().
protected void Page_Load(object sender, EventArgs e)
{
bool customResponse = true;
if (customResponse)
{
Response.Write("I am sending a custom response");
Response.End(); //this is what keeps it from continuing on...
}
}
The "easy" way to do it, with Response.End() is terrible for performance, throwing an exception which terminates the thread.
http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx
http://weblogs.asp.net/hajan/archive/2010/09/26/why-not-to-use-httpresponse-close-and-httpresponse-end.aspx
I had the same question and solved it this way. It's a two-step process: First call HttpApplication.CompleteRequest() and exit your processing. Next override Render() so that the base method is not called. The example code then becomes:
bool customResponse = true;
protected void Page_Load(object sender, EventArgs e)
{
if (customResponse)
{
Response.Write("I am sending a custom response");
this.Context.ApplicationInstance.CompleteRequest();
return; // Bypass normal processing.
}
// Normal processing...
}
protected override void Render(HtmlTextWriter writer)
{
if (!customResponse)
base.Render(writer); // Then write the page as usual.
}
It really depends what you're responding to, is it a posted Form field, authentication info etc...?
The method shown using Page_Load will work, but anything before that point in the page lifecycle will also execute.

Resources