I am trying to pass parameters to Jquery UI dialog for the new page. The new page has Page_Load method which connects to the database and displays the data. I am having issue with Page_Load method getting called first before $(document).ready. So parameter is empty. I appreciate any suggestions.
MainPage.aspx:
function ShowGraph(sId) {
var oid = sId;
$("#dialog")
.load('Graph.aspx')
.data("sId", sId)
$('#dialog').dialog('open');
}
<div id="dialog" title="My Dialog Title">
</div>
Graph.aspx:
$(document).ready(function () {
$get('<%= HiddenId.ClientID %>').value = $("#dialog").data('sId');
});
<asp:HiddenField runat="server" id="HiddenId"></asp:HiddenField>
code behind
protected void Page_Load(object sender, EventArgs e)
{
BL.GetNumbers(HiddenId.Value);
}
Pass parameter in query string like
function ShowGraph(sId) {
var oid = sId;
$("#dialog")
.load('Graph.aspx?sId='+sId)
$('#dialog').dialog('open');
}
and on page load event you can get it.
Related
I have a strange problem with Client Side validation after postback. I changed Combobox item that caused Selected Index event to fire(postback occurred). I clicked on 'Save' button after this event. Client side validation is not getting called instead it's calling server side btnSave_Click event.
Client side validation works fine if I don't change ComboBox. I would like to validate page controls on client side before calling server side method. Please let me know.
<asp:TextBox runat="server" ID="txtTitle" />
<telerik:RadComboBox ID="RadComboBox1" runat="server" DataValueField="location_id"
DataTextField="description" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged"
AutoPostBack="true" Width="250px" >
</telerik:RadComboBox>
<asp:Button ID="btnSave" name="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation="true"/>
Code behind:
protected void RadComboBox1_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
//some logic
}
protected void btnSave_Click(object sender, System.EventArgs e)
{
// save control values
}
Client Script
<script type="JavaScript">
$("#<%=btnSave.ClientID %>").click(function () {
// debugger;
var valid = true;
var errors = false;
var msg;
var msg = "<b>Please fill the Required fields:</b><br />";
if ($("#<%= txtTitle.ClientID %>").val().length == 0) {
msg += "Title is Required!\n";
errors = true;
}
if(errors){
alert(msg);
}
});
});
</script>
Your javascript validation method is doing nothing to stop the postback event from triggering.
Try this:
<script type="JavaScript">
$("#<%=btnSave.ClientID %>").click(function (evt) {
// debugger;
var valid = true;
var errors = false;
var msg;
var msg = "<b>Please fill the Required fields:</b><br />";
if ($("#<%= txtTitle.ClientID %>").val().length == 0) {
msg += "Title is Required!\n";
errors = true;
}
if(errors){
evt.preventDefault();
alert(msg);
return false;
}
});
});
</script>
Because your form controls reside in an UpdatePanel, the postbacks are causing event handlers attached to those controls to be lost. Use jQuery's event delegation to ensure the events still trigger, even after partial postbacks.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Change your event handler attachment to something like this:
$('body').on('click', '#<%=btnSave.ClientID %>', function () {
// rest of code
}
I used body as the initial selector, but you can choose any other selector that doesn't reside within the UpdatePanel.
I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.
I'm trying to create text box dynamically. so I cal it through the AJAX function.
This is my code:
Ajax function
function ChangedAdults(noofAdults) {
alert(noofAdults.value);
$.ajax({
type: 'POST',
dataType: 'json',
url: "/FlightBooking.aspx/Adults",
data: "{noOfAdults:'" + noofAdults.value + "'}",
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#AdultsList").html(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
code behind
[WebMethod]
public static string Adults(int noOfAdults)
{
FlightBooking obj = new FlightBooking();
obj.CreateAdultsList(noOfAdults);
string test= "";
return test.ToString();
}
private void CreateAdultsList(int noOfAdults)
{
int n = noOfAdults;
for (int i = 0; i < n; i++)
{
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "tb" + "" + i;
AdultsListPlaceholder.Controls.Add(MyTextBox); //error coming here
AdultsListPlaceholder.Controls.Add(new LiteralControl("<br />"));
}
}
But I receive an error:
Object reference not set to an instance of an object
What could cause this problem?
You can not dynamically add controls to a page using JQuery AJAX. Please get a good understanding of asp.net page lifecycle
In short this is how asp.net pages work.
Browswer sends request to server. i.e. http://localhost/test.aspx
Server creates a object for the page class. In this case the class is Test
The object renders the page. That means it converts the Controls of test.aspx to HTML which browsers can understand.
Server sends the rendered HTML back to Browser and destroys the object.
Browser displays the page.
So the server creates a new object every time it receives a page request.
However when a call to WebMethods is made using AJAX, no page object is created. This is why Webmethods have to be static.
I can see you are trying to create a object yourself and add the dynamic controls to that object. But this object is not related to the content displayed in the browser. So, adding controls to this object won't change anything that's displayed in the browser. For that to happen you have to post the whole page back. And if you return the rendered output of the object you created with Response.Write, that will return the HTML version of the whole page. Which is basically same as a PostBack
However, you can achieve AJAX based dynamic control rendering using UpdatePanel. Below is one way to do it
ASPX page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
Hope this helps.
You're mixing your paradigms. What would you expect this code to do? You can render controls in response to an AJAX call, but you must then manually insert the processed HTML into the DOM.
Call server using AJAX
Instantiate a dummy page container
Render server control
Return markup
Insert into DOM
Or, you can add new controls in response to a server event via a full postback or an async postback (e.g. an UpdatePanel).
In asp.net you can not create server control from jQuery or java-script.
Though you can call web-method from jQuery but you can't add any control from web method.
More details
Add new ASP.NEt server controls with jQuery?
One of the idea it to create textbox is to create html textbox
<input type="text" id="text1" ></input>
And post your value through jQuery ajax for manipulation.
Edit 1
Other way is to create all the controls at page load (If you know the maximum number)
Hide them initially
Show one by one on button click
And get the value on the server after postback.
Example:
add text to an asp.net textbox control with jQuery
AdultsListPlaceholder is null, you need to override its onload function to create children of this control.
e.g.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CreateAdultsList(5);
}
I have a web application in which I want to track two different views of the same page from google analytic.
From code behind I am managing the two different views..but didn't find the way to manage the below script from code behind.
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("XX-XXXXXX-XX");
pageTracker._setDomainName(".DOMAIN.com");
pageTracker._trackPageview();
} catch (err) { }
</script>
So how can I change this script dynamically from code behind...?
A hack will be to place two hidden fields in the aspx part
<asp:HiddenField ID="TrackerCode" runat="server" ClientIDMode="Static">
</asp:HiddenField>
<asp:HiddenField ID="DomainName" runat="server" ClientIDMode="Static">
</asp:HiddenField>
Then at page load assign them
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TrackerCode.Text = "XX-XXXXXX-XX";
DomainName.Text = ".DOMAIN.com";
}
}
And finally place your script at the bottom of the page. ( After the labels we created )
<script type="text/javascript">
try {
var tcode = document.getElementById("TrackerCode").value;
var domain = document.getElementById("DomainName").value;
var pageTracker = _gat._getTracker( tcode );
pageTracker._setDomainName( domain );
pageTracker._trackPageview();
} catch (err) { }
</script>
Declare one function and define all your logic inside this function.
And call that function when the DOM is ready or on window.onload.
window.onload=function(){
//your function called it here or right your code here
}
Hope it will work
having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>