I am not so familiar with JavaScript, for that reason I need your help and advice! I have the following code in my asp button when is clicked. When the confirm box is displayed the user has two choices either to select OK or Cancel. The following code works in both of cases either OK or Cancel.
protected void cancel_Click(object sender, EventArgs e)
{
string url = "../../Default.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "confirm('Data is not saved'); window.location.href = '" + url + "';", true);
}
However, what I am trying to do is to perform an if/then/else statement using JavaScript inside ClientScript function, and I don't know the correct syntax of that. e.g what I am trying to do
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "javascript:if(confirm('Data is not saved')== true) return {document.location.href = '../../Default.aspx'}; else {document.location.href = '../../Current.aspx'};", true);
Any advice would be appreciated!
Try the script before you add it server side, it easier to debug that way.
Here´s two ways to write the if statement;
if (confirm('Data is not saved')) {
window.location.href = '../../Default.aspx';
} else {
window.location.href = '../../Current.aspx';
}
or even;
window.location.href = confirm('Data is not saved') ?
'../../Default.aspx' : '../../Current.aspx';
UPDATE
<asp:Button ID="cancel" runat="server" Text="Cancel" CausesValidation="false"
onClientClick="window.location.href = confirm('Data is not saved') ? '../../Default.aspx' : '../../Current.aspx';"
/>
Also note that you should rather use window.location than document.location.
Related
Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function
JavaScript function:
function IsAgentInProgram()
{
var optStatus = "<%=AgentOptInStatus%>";
if (optStatus == "True")
alert("You are opted in!");
else
alert ("You are opted OUT");
}
C# code behind
public bool AgentOptInStatus;
private void Page_Load(object sender, System.EventArgs e)
{
this.AgentOptInStatus = true;
}
This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"
Am I missing something?
You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.
<asp:HiddenField ID="hdnfldVariable" runat="server" />
JS:
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
c# :
string selected = hdnfldVariable.Value.ToString();
Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.
I need to call confirmation message box from codebehind as the user select data from dropdown list and when the selected data is 1 for example a confirmation box will appear to the user to confirm his action
so I did that as below in the code behind I called this JavaScript method:
if (dropdownlist1.SelectedValue == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);
}
The script function:
<script type="text/javascript">
function CallConfirmBox() {
if (confirm("هل تريد ان تفصل الباليت؟")) {
alert("سيتم فصل الباليت!");
PageMethods.getdata(onSuccess, onError);
function onSuccess() {
alert(data);
}
function onError() {
alert(errorMessage);
}
}
} else {
//CANCEL – Do your stuff or call any callback method here..
alert("done!");
}
}
And I've added the below line at the beginning of the HTML code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
and Here is the code behind function that is called from script :
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void getdata()
{
int nRowsCheck = cMDP.Update_Segregation_PalletPart(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Update_Segregation_Pallet(nPalletNo, nUserID);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_PalletPart_Delete(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_Pallet_Delete(nPalletNo);
}
}
}
}
But I've got the below error:
Page Methods is undefined when run the script !!
Please help as I need some support
First, you'll have to remove one } before the else in your JavaScript.
Change in your code-behind:
if (dropdownlist1.SelectedValue == "1")
For the main problem: Page Methods is undefined:
It seems from your comment that you're using a User Control (ascx). Page Methods cannot be used in a User Control. Please refer to these questions:
PageMethods is not defined
ASP.NET AJAX Page Methods from UserControl
The easiest solution is to use an aspx WebForm instead of an ascx User Control. That's what I've tested and worked.
Or you can use a WebService, as specified in the following question:
Alternate way to use page method inside user control asp.net
But the link to the sample is not working anymore.
Or you can try to use this project that tries to bring ASP.NET AJAX Page Methods to UserControls:
Control Methods for ASP.NET AJAX
You have two problems:
Change you javascript code:
PageMethods.getdata(onSuccess, onError);
function onSuccess(data)
{
alert(data);
}
function onError(data)
{
alert(data);
}
And you code behind getdata method must be a public static string function:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getdata()
{
//Do some things
return " Operations done successfully!";
}
I have an alert that I want to send the user only on his first entry to the website. The condition is in c# and that's the code I used. It doesn't send the alret. What should I do?
if ((string)Session["alert"] == null) {
Response.Write("<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>");
Session["alert"] = "done";
}
If you are using ASP.NET Web Forms u can use ScriptManager like this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);
If you set the last parameter to true the content will get wrapped in script tags.
Your code would look like this:
if ((string)Session["alert"] == null) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);
Session["alert"] = "done";
}
Try this code.
ASPX
<body>
<form id="form1" runat="server">
<asp:Literal id="ltrMessage" runat="Server"/>
</form>
</body>
ASPX.CS Code
if ((string)Session["alert"] == null) {
ltrMessage.Text="<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>";
Session["alert"] = "done";
}
To be considered, your literal item should be added to the end Body html tag.
I hope that helps.
I have a LinkButton in masterpage and on click of LinkButton , I am redirecting to, say, Page1.aspx . On Page1.aspx , I have a button1. On click of that button1, I am opening new window, not affecting data of the Page1.aspx.
But when I click on LinkButton of masterpage, redirecting to Page1.aspx and from code behind,clicking button1 , Page1.aspx 's data gets changed.
How to prevent this. I am providing my code.
LinkButton on Masterpage :
<asp:LinkButton ID="lnkAppointMent" runat="server" OnClick="lnkAppointMent_Click"><span>Appointment Scheduler </span></asp:LinkButton>
click Event of LinkButton :
protected void lnkAppointMent_Click(object sender, EventArgs e)
{
Session["PhoneCenter"] = "Appointment";
Response.Redirect("PhoneMessage.aspx");
}
PageLoad of redirecting page(PhoneMessage.aspx) :
protected void Page_Load(object sender, EventArgs e)
{
fillCustomTypeMessages();
if (!Page.IsPostBack)
{
.
.
.
else if (Session["PhoneCenter"].ToString() == "Appointment")
{
btnScheduleAppointments_Click(btnScheduleAppointments, null);
}
.
.
.
Button on PhoneMessage.aspx :
<div style="float: right; padding-right: 120px">
<asp:Button ID="btnScheduleAppointments" runat="server" OnClick="btnScheduleAppointments_Click"
CssClass="button" Text="Schedule Appointments" ToolTip="Open appointment scheduler" />
</div>
RaisPostBack method on PhoneMessage.aspx :
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
try
{
base.RaisePostBackEvent(source, eventArgument);
}
catch (Exception ex)
{
}
.
.
p.s : when I click on btnScheduleAppointment , source will be Schedule Appointments and if I click on lnkAppointMent , source will be <span>Appointment Scheduler </span> even if I am calling btnScheduleAppointment on click of lnkAppointMent.
Click event of button :
protected void btnScheduleAppointments_Click(object sender, EventArgs e)
{
if (!Permissions.checkPermissions(Session["employeeloggedin"].ToString(), "PHMSGVMD"))
{
ScriptManager.RegisterStartupScript(this, Page.GetType(), "OnLoad", "alert('You must have the Phone Messages: View and Modify permission to schedule appointments!')", true);
}
else
{
string script = String.Format("openNewWin('" + "phonescheduler.aspx" + "')");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "openNewWin", script, true);
}
}
Script :
function openNewWin(url)
{
alert(url);
var open_link = window.open('', '_blank');
open_link.location = url;
}
Any clarification needed. Please comment.
It took me some time to simulate your problem. Have you tried to modify the LinkButton href or atributes after the Page1.aspx has been loaded?
I am assuming your Page1.aspx is your PhoneMessage.aspx, so when you click lnkAppointMent from the master page, it goes to "PhoneMessage.aspx" and execute the method, then if you click it again it will only post back instead of do what it did before, basically, you you need to redirect to "PhoneMessage.aspx" again.
So why dont you modify the part like this:
else if (Session["PhoneCenter"].ToString() == "Appointment")
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "NoExec", String.Format("document.getElementById('lnkAppointMent').href=window.location.href;"), true);
btnScheduleAppointments_Click(btnScheduleAppointments, null);
}
That would make the link redirect to the Page1.aspx again, and do the same without postback. It is not the most elegant solution, but it does the job in your case. Just make sure to have Session["PhoneCenter"] = "Appointment";
So it is not the answer to your question but I think is a solution to your problem.
It worked for me, I hope It helps! Let me know what you think.
Basically I want to set the default date on a jQuery calendar. I have a little script that runs fine when the page loads.
<script type="text/javascript">
$(function () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
});
</script>
However, when the user changes the value on a combo box, the page posts back and runs some code which causes the value of CalendarDefaultDate to update. The problem is that even though the value of the property has changed, it doesn't get reflected on the page.
Any ideas how to fix this? Many thanks.
Update 1. Tried using the ClientScriptManager as advised. (with no joy)
StringBuilder builder = new StringBuilder();
builder.AppendLine("$(function(){var calendarPicker = $(\"input[name='ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker']\")");
builder.AppendLine("if (calendarPicker.val() == '') {");
builder.AppendLine("calendarPicker.datepicker(\"option\", \"defaultDate\", '" + CalendarDefaultDate + "')");
builder.AppendLine("}});");
Page.ClientScript.RegisterStartupScript(GetType(), "CalenderDefaultDate", builder.ToString(), true);
You can use the ClientScriptManager to run your function on the reload:
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Try to declare your function on aspx file this way.
<script type="text/javascript">
function assignCalendar () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
};
</script>
Then in code behind call it like below:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "assignCalendar ", "<script type='text/javascript'>assignCalendar();</script>", false);
If you put it on PageLoad event i think it will work