I want to execute the Add button click event(server side) from client side.
This is my javascript function
function validateinput() {
var arrTextBox = document.getElementsByTagName("input");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].value == "") {
retVal = 0;
}
}
if (retVal == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
return true;
__doPostBack(btnAddItem);
}
}
I am calling the server side code only when alert("Validation Sucess") and returns true.
This is my server side code
protected void Page_Load(object sender, EventArgs e)
{
txtbox1.Attributes.Add("onkeydown", "if(event.keyCode) {if (event.keyCode > 57 && event.keyCode <= 90) return false; } else {return true};");
if (!IsPostBack)
{
//The code is too big to be posted
}
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
if (btnAddItem.Text == "Add Item +")
{
if (textbox1.text== "")
{
Addtogrid();
}
}
}
}
Am I doing it the right way? as I am not getting the expected results. Also I get an error at Page.GetPostBackEventReference(btnAddItem); saying ClientScript is a recommended way . When I try to use ClientScript.GetPostBackEventReference(btnAddItem); it throws an error stating ClientScript is not recognised.
Please help
The onclick event of an asp:button object will call the client validation if you set it up with a validtion control. If you have not set up the onclick event to the button it is not going to know what method to call. If you have set up the onclick then the javascript call is not needed. If you set up a validation control to use the validation script and the client side validation .net will handle the postback call. And looking at your script you may be better served using a required field validator than your custom script.
Are you sure you need the GetPostBackEventReference code in the page load method? _doPostBack() doesn't the target object to be referenced, just the name.
Edit: Why are you calling return true before calling _doPostBack()?
Edit 2: There are 2 ways to call GetPostBackEventReference, 1) from your .NET code here but this is an obsolete method and the client side script version is recommended, 2) from your client side script here. I can't tell which method you are using because you didn't post the page load code. I don't see a reason to call it based on the other code you posted. The call to _doPostBack() can operate without getting the post back reference for a control.
Remove the call to GetPostBackEventReference and change your javascript to look like this:
function validateinput() {
var arrTextBox = document.getElementsByTagName("input");
var ddlTextBox = document.getElementsByTagName("select");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].getAttribute("IsMandatory") == "Y" && arrTextBox[i].value == "") {
retVal = 0;
}
}
if (retVal == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
__doPostBack('btnAddItem', '');
return true; // This shouldn't be needed but it does need to come after _doPostBack()
}
}
Edit 3: Try the following code for the button:
<asp:Button ID="btnAddItem" runat="server" onclick="btnAddItem_Click" OnClientClick ="javascript:validateinput(); return false;" Text="Add Item +" Width="85px" />
The OnClientClick code needs to return false if you don't want it to post back to the form. Even if you return false from a called JavaScript method, it will still post back. This has never made sense to me but I've learned it through repeatedly having this same issue.
Related
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!";
}
My javascript code:
function Confirm()
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("UserID already exists...Do you want to update information?"))
{
confirm_value.value = "Yes";
}
else
{
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
My asp.net code on button click:
protected void Btn_Create_Click(object sender, EventArgs e)
{
bool check;
_objClsCreateUsers = new ClsCreateUsers();
check = _objClsCreateUsers.CheckUserID(Txt_UserID.Text);
if (check == true)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
_objClsCreateUsers.UpdateData(Txt_UserID.Text, Txt_UserName.Text, Txt_Password.Text, Lst_Department.Text, Convert.ToDateTime(Txt_ExpiredOn.Text), Convert.ToBoolean(Lst_IsAdmin.Text));
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Updated Successfully')", true);
ClearAll();
enter code here
}
else
{
Txt_UserID.Text = "";
}
}
else
{
_objClsCreateUsers.InsertData(Txt_UserID.Text, Txt_UserName.Text, Txt_Password.Text, Lst_Department.Text, Convert.ToDateTime(Txt_CreatedOn.Text), Convert.ToDateTime(Txt_ExpiredOn.Text), Convert.ToBoolean(Lst_IsAdmin.Text));
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('User Created Successfully')", true);
ClearAll();
}
}
I am having problem in catching the output value of javascript function's output.
Javascript runs after the complete code of button click is run. I want it to run in the middle of code.
Thanks.
Considering that it's a create account kind of form, An ideal way as per me should be as below
You should make an ajax call when the value in the UserID textbox is changed. Or Bind Server side event for the text control (hope you are using server controls). In this AJAX call you can get the result from server if the user id already exists or not and show the message at the same time itself.
On submit, you should again check if the user ID already exists, and update the information straightforward without confirmation. If the ID does not exists then Insert it
How can I retrieve value from javascript function in codebehind, on page load ..
javascript function like :
<script type="text/javascript">
function isIFrame() {
var isInIFrame = (top.location != self.location);
if (isInIFrame) {
return "inside";
}
else {
return "outside";
}
}
</script>
and code behind like :
protected void Page_Load(object sender, EventArgs e)
{
string resutOfExecuteJavaScript = "";
// resutOfExecuteJavaScript = isIFrame(); // from javascript
if (resutOfExecuteJavaScript == "inside")
{
// do something
}
else
{
// do something
}
}
thank you.
You cannot directly call a client side javascript method from server side code . For that first you need to assign the function result to value of some hidden variable and then access it in server side
Suppose you have an hidden field like this
<input type="hidden" runat="server" id="hdnVal"/>
then you can set the value as below
document.getElementById("hdnVal").value=isIFrame();
then at serve side
string resutOfExecuteJavaScript = hdnVal.Value;
using _doPostBack, you can solve this one
<script type="text/javascript">
function isIFrame() {
var isInIFrame =(top.location != self.location);
var result;
if (isInIFrame) {
result="inside";
}
else
{
result ="outside";
}
__doPostBack('callPostBack', result);
</script>
</head>
In code behind section
protected void Page_Load(object sender, EventArgs e)
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (IsPostBack)
{
string eventTarget = this.Request["__EVENTTARGET"];
string eventArgument = this.Request["__EVENTARGUMENT"];
if (eventTarget != String.Empty && eventTarget == "callPostBack")
{
if (eventArgument == "inside"){
//do something
}
else if(eventArgument == "outside")
{
//do something
}
}
else
{
// set the button click
btnclick.Attributes.Add("onClick", "isIFrame();");
}
}
Below link will help you out to get more idea.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=203
in javascript file or your script add :
function SetHiddenVariable()
{
document.getElementById(inpHide).value= "value";
}
in .aspx add this tag:
<input id="inpHide" type="hidden" runat="server" />
in aspx.cs (c# file) add :
anyVariable = inpHide.Value;
I have a function in server side which fills a dropdownlist. I call this function with a button click on client side using PageMethods in Javascript like this:
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<asp:Button runat="server" ID="SearchButton" Text="Search" OnClientClick="SearchButtonClick();return false;"/>
<asp:DropDownList runat="server" ID="SearchCityDropDownList" Width="100px"/>
And
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
Server side function:
[WebMethod]
public static string SearchButtonActivity()
{
string result = "Everything is OK!";
foreach (string value in getCityList())
{
SearchCityDropDownList.Items.Add(new ListItem(value));
}
return result;
}
When I run this code and click on the button it just shows the "Everything is OK!" alert and
dropdownlist still empty.
Please help me to solve this problem, I think this is a post back problem because when I debug the code, items of dropdownlist are full but they don't show up in the dropdown.
Thank you
This will not work, how you have it setup. You could do an update panel, but that would be overkill, IMO. The problem is that you are making an AJAX call which just goes back to the server and returns to the client. The page, and thus the control, never get back to the server to get re-rendered.
Instead, you need to bind the result from your onsuccess callback to your dropdown list. So your web method needs to change:
[WebMethod]
public static string SearchButtonActivity()
{
var result = new List<string>();
foreach (string value in getCityList())
{
result.Add(value);
}
return result;
}
And then your onSuccess client side callback needs to handle it:
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
SearchCityDropDownList.options.length = 0;
for (var i==0;i<result.length;i++) {
AddOption(result[i], i);
}
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
function AddOption(text, value) {
var option = document.createElement('option');
option.value = value;
option.innerHTML = text;
SearchCityDropDownList.options.add(option);
}
You can retrieve the value selected, server side in this fashion:
string selectedVal = Request[SearchCityDropDownList.UniqueID]
Thanks to this so post for the guidance: Getting the value of a DropDownList after client side javascript modification
I have a weird problem. I use JavaScript on a Sharepoint page. I reference following JavaScript code:
var statusId = '';
var notifyId = '';
function AddNotification(message) {
notifyId = SP.UI.Notify.addNotification(message, true);
}
function RemoveNotification() {
SP.UI.Notify.removeNotification(notifyId);
notifyId = '';
}
function AddStatus(message) {
statusId = SP.UI.Status.addStatus(message);
SP.UI.Status.setStatusPriColor(statusId, 'red');
}
function RemoveLastStatus() {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
function RemoveAllStatus() {
SP.UI.Status.removeAllStatus(true);
}
Then when the user clicks a button, a notification should appear with the message "please wait...". Before the calling C# method exits, it should remove the notification. Like this:
protected void SaveButton_Click(object sender, EventArgs e)
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "Notif", "AddNotification('" + Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.PleaseWaitString) + "');", true);
//Busiess logic...
if (ActivityDate.SelectedDate == null || //Date required
ActivityProjectnumber.SelectedIndex == 0 || //Project number required
ActivityActivity.Text == string.Empty || //Activity description required
EndTime.SelectedDate.Hour < StartTime.SelectedDate.Hour || //
EndTime.SelectedDate.Hour == StartTime.SelectedDate.Hour && //Start time should not be less or equal end time
EndTime.SelectedDate.Minute <= StartTime.SelectedDate.Minute) //
{
StatusSetter.SetPageStatus(Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.CheckRequiredFieldsString), Core.Classes.ResourceHelper.LoadResource(Core.Classes.ResourceName.WarningString), this.Controls);
return;
}
//If business logic passed, save item.
SaveItem();
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "Notif", "RemoveNotification();", true); //Problem lies here...
}
The notification is displayed when the user clicks the button. But it doesn't disappear. I debugged the code and the corresponding line is definitely being executed. I suspect it has something to do with me using ScriptManager.RegisterStartupScript two times in one method. But I don't know how to do it otherwise.
You need to give different names to each script (the 3rd parameter of RegisterStartupScript).