Prevent Full Postback from __doPostBack - c#

I have a content page that contains the following...
UpdatePanel1 - containing Error Display Divs
contains update triggers for both buttons
UpdatePanel2 - containing process 1 with an asp:button
updatePanel3 - containing process 2 with an asp:button
JavaScript that presents the user with a Popup confirm Jquery Messagebox based on the process they are executing.
UpdatePanel 2 or 3 becomes visible based on the users selection from the menu options.
When I click a button the messagebox pops and the page is processed correctly using __doPostback from the messagebox response and the page does a full postback.
I would rather the page do a partial postback and the content it had and display the Error Display Divs if there was an error. Any assistance would be appreciated.
nothing special about the button
<asp:Button ID="ResetSomething" runat="server" Text="ResetSomething" Width="275px" />
here is the content page script block
<script type="text/javascript" language="javascript">
<!--
function pageLoad() {
setform();
};
function setform() {
var reset1_button = $('input[id*=ResetSomething]');
var reset2_button = $('input[id*=ResetSomethingElse]');
reset1_button.click(function() {
var element = $(this);
$.prompt('Message1', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
submit: function(v, m, f) { submit_reset_callback(v, m, element); }
});
return (false);
});
var submit_reset_callback = function(result, messages, element) {
if (result) { __doPostBack("ResetSomething");}
return (false);
};
reset2_button.click(function() {
var element = $(this);
$.prompt('Message2', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
submit: function(v, m, f) { submit_update_callback(v, m, element); }
});
return (false);
});
var submit_update_callback = function(result, messages, element) {
if (result) { __doPostBack("ResetSomethingElse"); }
return (false);
};
};
-->
</script>
this is the code behind for the OnInit:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreLoad += (sender, args) =>
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (!IsPostBack) { return; }
string __targetaction = this.Request["__EVENTTARGET"];
string __args = this.Request["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(__args)) return;
if (__targetaction == "ResetSomething")
{
ResetSomething();
}
if (__targetaction == "ResetSomethingElse")
{
ResetSomethingElse();
}
this.upnlNotifications.Update();
};
}

Define the function below and replace your __doPostBack calls with doPostBackAsync(controlId, null).
function doPostBackAsync(eventName, eventArgs) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
prm._asyncPostBackControlIDs.push(eventName);
}
if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
prm._asyncPostBackControlClientIDs.push(eventName);
}
__doPostBack(eventName, eventArgs);
}

The controlId should be the id of the button to generate async postback else full postback occurs in the page.
For that you can use the clientidmode as static e.g
<asp:Button ID="button1" runat="server" ClientIDMode="Static"/>
//then you can use below code
_doPostBack('button1', '');//clientidmode forces buttonid = id given by us
Check its correct?
If so then you can get the async postback instead of a full page postback.
This helped me.
Thanks #Tim for his comment.

Related

checkboxes not styled after ajax call

I have a script file scripts.js with a function that styles all checkboxes in page. This file is referenced in the master page.
There is a user control and a aspx test page for it. On page load, the UC shows a list of checkboxes and the style is applied.
On clicking a button, an ajax call gets a list from database and binds some more checkboxes to the page. But for the new checkboxes, the style is not applied. What could be going wrong.
scripts.js:
function selectcheckBtn() {
alert(1);
if ($("input:checkbox").prev("span").length === 0) {
alert(2);
$("<span class='uncheked'></span>").insertBefore("input:checkbox")
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
}
ctrl.ascx:
<script>
function ShowMore() {
$.ajax({
url: "/_layouts/15/handlers/ShowMore.ashx",
data: {},
success: function (msg) {
//append new chkbox list to existing list. It is hidden at first and later faded in.
$(".divList").append(msg);
selectcheckBtn();
$(".hideDiv").fadeIn(300).removeClass("hideDiv");
},
error: function (msg) {
alert("An error occurred while processing your request");
}
});
}
</script>
Show more
On page load both alerts pop. But on clicking 'Show More', only alert(1) pops.
There are no errors in browser console.
Rendered HTML:
//with style applied to chkboxes on page load
<div><span class="uncheked"></span><input type="checkbox" runat="server" id="406">
<label>Compare</label></div>
//with no style applied to new chkboxes
<div><input type="checkbox" runat="server" id="618"><label>Compare</label></div>
I did not understand why the if condition wasn't true in selectcheckBtn();, for the new chkboxes. So, added a new class for the checkboxes and wrote this workaround.
Now calling this function instead of selectcheckBtn(); in the ajax code, worked.
function StyleCheckBox() {
$(".chkBx").each(function () {
if ($(this).prev("span").length === 0) {
$("<span class='uncheked'></span>").insertBefore($(this));
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
});
}

JavaScript Abnormal Behaviour [duplicate]

Is it possible to use the onclientclick property of a button to do a clientside check. If the check returns true, then fire the onclick event. If the clientside check returns false, don't fire the onclick event.
Is that possible?
UPDATE:
These 2 work:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
The next 2 do not work:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
It submits the form both times.
Why is that?
You want to add return inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.
<asp:button ID="Button1" runat="server" OnClick="Button1_Click"
OnClientClick="return checkValidation()" Text="Submit" />
<script type="text/javascript">
function checkValidation() {
return confirm('Everything ok?');
}
</script>
Sure. If you use return false within your OnClientClick it will prevent any navigation from happening. So you're code would look like:
<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Yes you can, In onclientClick function call use preventDefault()
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
e.preventDefault();
}
}
OR
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
return false;
}
}
In the server page create the button:
var button1 = new Button();
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );
//Contains the server code
private void saveBtn_ServerClick(object sender, EventArgs e)
{
//do something if ClientClick returns true
}
//Contains the JS code for the page
LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =#"<script type='text/javascript'>
$(document).ready(function(){
function CheckValidationOnClient(){
if(!ValidatePage()){
return false;
}
else{
return true;
}
};
});
</script> ";
private string SetJsForSaveBtn()
{
var jsfunc = #" return CheckValidationOnClient()";
return jsfunc ;
}
I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.
However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.
namespace My.WebControls {
[ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
public class LinkButton : System.Web.UI.WebControls.LinkButton {
private bool _postback = true;
[Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
public bool AutoPostBack { get { return _postback; } set { _postback = value; } }
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
if(!AutoPostBack){
this.OnClientClick = "return false";
}
base.Render(writer);
}
}
}
Many attributes should need to be handled in a ViewState but in this case I think we are good;

Detecting focussed control in C#

I have an update panel which is causing a postback on part of the page and after postback the control that had focus (which is not in the update panel) loses focus. How can I identify which control had focus and save that value, so that I can refocus to it when the page reloads. Thank you.
First I bind the focus on all input and keep the last focused control ID. Then after the UpdatePanel finish the load, I set the focus to the last one
// keep here the last focused id
var LastFocusedID = null;
function watchTheFocus()
{
// on every input that get the focus, I grab the id and save it to global var
$(":input").focus(function () {
LastFocusedID = this.id;
});
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
// after the updatePanel ends I re-bind the focus, and set the focus
// to the last one control
function EndRequest(sender, args) {
if(LastFocusedID != null)
$('#' + LastFocusedID).focus();
watchTheFocus();
}
jQuery(document).ready(function()
{
watchTheFocus();
});
The only think is that I use jQuery to make it, but I present here my idea, you can make it with little more code with out jQuery.
You can get what element has focus with javascript using the activeElement and hasFocusproperty to HTMLDocument object.It might not be supported by all since it's HTML5.
You can solve like this
var last_focused = null;
$(function () {
//store last focused element.
$("input").live("focus", function(){
last_focused = $(this);
});
});
//in Script manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args)
{
if(last_focused != null)
{
last_focused.focus();
}
}

How to call c# method with parameter from Jquery? ASP.Net 2.0

I show modal popup window in default.aspx page so:
<a id="popup" href="../Popup/Keywords.aspx">edit</a>
Jquery function:
$(document).ready(function () {
$('a#popup').live('click', function (e) {
var page = $(this).attr("href")
var $dialog = $('<div></div>')
.html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
.dialog({
autoOpen: false,
modal: true,
height: 450,
width: 'auto',
title: "Edit Employee",
buttons: {
"Close": function () { $dialog.dialog('close'); }
},
close: function (event, ui) {
__doPostBack('<%= grdReportKeywordsRefresh(report_id) %>', '');
}
});
$dialog.dialog('open');
e.preventDefault();
});
});
How to call "grdReportKeywordsRefresh" method with parameter "report_id" right?
Why controls of Default.aspx page are not displayed in popup window?
report_id:
private String r_id;
public Int32 report_id
{
get { return r_id != null ? Convert.ToInt32(r_id) : 0; }
set { r_id = value; }
}
grdReportKeywordsRefresh method:
protected void grdReportKeywordsRefresh(int report_id)
{
grdKeywords.DataSource = conn.GetKeywordsByRepId(report_id);
grdKeywords.DataBind();
}
People are right, you're mixing stuff :)
It should go like this:
<script type="text/javascript">
this is what you call:
__doPostBack('updateMyGrid', '')
</script>
in codebehind (using VB.NET, if you use C#, I'll change it)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack AndAlso Page.Request("__EVENTTARGET") = "updateMyGrid" Then
'rebind your grid here
End If
End Sub
c# (just frome head)
protected void Page_Load(object sender, EventArgs e) {
if(IsPostBack && Page.Request["__EVENTTARGET"] == "updateMyGrid") {
//rebind here
}
}
You're mixing client and server code.
You're also loading another page altogether into your pop-up, so it's not surprising it's not showing anything from default.aspx.
You could set a value in a hidden field when you close the pop-up, then force the postback & on the server, check if the hidden field value is set and call the function if it is.
Simon
Where is report_id defined? You cannot use variables that are set in javascript because server side code (<%= %>) gets executed when the page is rendered by the server.

How to handle Yes No dialog that was pop-up using Javascript on button click

I am having an update button on my from on clicking update i would like to prompt the user as Do you want to delimit the record with Yes and No buttons. If the user clicks on Yes i would like to execute the code which can delimit the record if not just update the record.
My sample code
protected void btnUpdate1_Click(object sender, EventArgs e)
{
EmpID = Convert.ToInt32(HiddenField1.Value);
if (ID == 2)
{
oEmployeePersonalData.EmpID = EmpID;
oEmployeePersonalData.PhoneNumberTypeID = ddlPhoneType.SelectedValue;
oEmployeePersonalData.PhoneNumber = Convert.ToInt64(txtph1.Text);
oEmployeePersonalData.EndDate = DateTime.Today.AddDays(-1);
//As per my requirement if i click on yes i would like to execute this code
if (oEmployeePersonalData.PhoneDetailUpdate())
{
}
// If No different code
if(confirm("Would you like to delimit the record"))
{
//Delimit record code or return true;
}
else
{
return false;
}
Add following javascript function in the header of the page
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {
}
else {
return false;
}
}
</script>
and then attach the event to button
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" OnClientClick="return update();"/>
var ans = confirm("Do you want to delimit the record?")
if (ans){
//clicked on yes
}
else{
return false;
}

Categories