System.Web.UI.ScriptManager.RegisterStartupScript only getting executed once - javascript

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).

Related

How to call javascript function from code behind on button click and store its output and proceed further

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

Avoid Postback when calling code behind

So I'm trying to do some input validation on an ASP form and if the validation fails it's not supposed to try and submit the form but simply show a modal window (bootstrap) with the error and then let the user fix the error/fill in the blanks they forgot.
But whenever I press my HTML button (or ASP button I've tried both) it shows the modal window and does a postback right after. I can see that this happens because I have to upload fields that lose their file references and I have a dynamically created dropdown which also resets.
I would like to find a way to get around this but after looking at several SO answers I havne't found a solution.
Using the popular return false; solution makes the submit button stop working all together.
My HTML:
<div class="row">
<script>
function activityAdd() {
__doPostBack('Activity_Add', 'postback');
};
</script>
<asp:Button CssClass="btn btn-success" Style="font-size: 20px;" runat="server" OnClientClick="activityAdd();" Text="Submit"/>
<a class="btn btn-danger" runat="server" href="~/Index" style="font-size: 20px;">Cancel</a>
</div>
C# Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "CreateDepartmentDropdown", "$(document).ready(function(){CreateDepartmentDropdown(" + GetDepartmentDropdownList() + ");});", true);
ScriptManager.RegisterStartupScript(this, typeof(Page), "RegisterDatepickers", "$(document).ready(function(){RegisterDatepickers();});", true);
//Activity_Add.Attributes.Add("onClick", "return false;");
//Activity_Add.Click += Activity_Submit_Click;
if (Request["__EVENTARGUMENT"] == "postback")
{
SubmitActivity();
}
}
And the Submit Method:
public bool SubmitActivity()
{
bool InputValidated = true;
List<String> ErrorMessages = new List<String>();
int fye = Int32.Parse(fye_dropdown.Value);
String activityName = activity_name_field.Value;
String[] ax_accounts = (ax_account_numbers_field.Value.Contains(',') ? ax_account_numbers_field.Value.Split(',') : new String[1] { ax_account_numbers_field.Value });
if (activityName.Length == 0)
{
InputValidated = false;
ErrorMessages.Add("The Activity Name is not filled.");
}
String activity_responsible = responsible_field.Value;
int department;
if (department_dropdown_selected_value.Value.Length == 0)
{
department = 0;
}
else
{
department = Int32.Parse(department_dropdown_selected_value.Value);
}
DateTime start;
DateTime end;
// Since the dates are formatted for Americans we will rearrange day and month in code.
// Otherwise the JavaScript that checks the two Calendars break and we can't parse a DateTime object.
try
{
String[] date = datepicker_start.Value.Split('/');
String parseString = date[1] + "/" + date[0] + "/" + date[2] + " 00:00:00 AM";
start = DateTime.Parse(parseString);
}
catch (Exception)
{
InputValidated = false;
ErrorMessages.Add("The Start Date was not formatted right. Please only click in the box and choose a date from the calendar.");
}
try
{
String[] date = datepicker_start.Value.Split('/');
String parseString = date[1] + "/" + date[0] + "/" + date[2] + " 00:00:00 AM";
end = DateTime.Parse(parseString);
}
catch (Exception)
{
InputValidated = false;
ErrorMessages.Add("The End Date was not formatted right. Please only click in the box and choose a date from the calendar.");
}
if (ax_accounts[0].Length == 0)
{
InputValidated = false;
ErrorMessages.Add("You need to add at least one AX Account for the Activity.");
}
if (!description_upload.HasFile)
{
InputValidated = false;
ErrorMessages.Add("Please choose a file to upload for the Detailed Description of the Activity");
}
if (!estimation_upload.HasFile)
{
InputValidated = false;
ErrorMessages.Add("Please choose a file to upload for the Estimation of the Activity.");
}
if (InputValidated == false)
{
StringBuilder sb = new StringBuilder();
sb.Append("An Error happened while submitting the activity. Please see below for details.");
sb.Append("<br>");
foreach (String msg in ErrorMessages)
{
sb.Append("- ").Append(msg).Append("<br>");
}
String jsExec = Util.ModalAlert(sb.ToString(), "#error_modal", ".modal-body");
ScriptManager.RegisterStartupScript(Page, GetType(), "error_modal_show", jsExec, false);
return false;
}
else
{
byte[] descriptionBytes = description_upload.FileBytes;
String descriptionFileName = description_upload.FileName;
byte[] estimationBytes = estimation_upload.FileBytes;
String estimationFileName = estimation_upload.FileName;
String msg = Util.Alert("Success");
Response.Write(msg);
return true;
}
}
But that doesn't work as expected either. All the fields mentioned earlier still reset. It's infuriating me to no end because it's going to be a frustrating experience for the user. Any idea on how to approach this problem?

How to reload a jquery Datatable after the user finished editing operation?

I am using ASP.NET MVC4. I want to refresh my table after a user has edited a column.(I do not want to make it like when a user press enter, I want to refresh it when a user finishes writing and clicks somewhere else.This is my jquery script :
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#result').dataTable().makeEditable();
});
</script>
And this is my controller:
public string UpdateData(string id,string value, int columnPosition)
{
ObjectId oid = new ObjectId(id);
var query = from n in ObjectMongoCollection.AsQueryable<User>()
where n.UserId == oid
select n;
User user = query.FirstOrDefault();
if (user == null)
{
return "error";
}
else
{
if (columnPosition == 0)
{
user.Name = value.Trim();
}
else if (columnPosition == 1)
{
user.Surname = value.Trim();
}
else
{
user.Number = value.Trim();
}
ObjectMongoCollection.Save(user);
return "successfull";
}
}
I do not know which function should I use and where to put this function on my code. (I do not know why but fnDraw method does not work) Can you help me? Thanks.
Use:
$(document).ready(function () {
$('#result').dataTable().makeEditable();
$('#element').keyup(function(e) {
if(e.keyCode == 13) {
location.reaload();
}
});
if($('#element').click()) {
location.reaload();
}
if($('#element2').click()) {
location.reaload();
}
});
This method takes an optional parameter (true \ false), true means reload from the server rather from the cache, the default is false, meaning by default it uses the web browser's cache.
Edit:
Notice that 13 checks if enter key was pressed, number 13 = enter key.
You can use this formate
$('#myTable').DataTable().ajax.reload();

if statement in jQuery not working in Chrome or Safari

I have the following code that is working in IE 8 but not in Chrome or Safari:
$(document).ready(function(){
$('.goRedIMG').on('click',function(event){
var ischecked = false;
var isOKtoSubmit = true;
var alertMessage = 'No tools have been selected';
var statusvar = '';
var transferstatusvar = '';
var action = $('#uTransaction option:selected').html();
$('.chkaction').each(function() { //loop through each checkbox
statusvar = $(this).closest('tr').children('.recordStatus').html();
transferstatusvar = $(this).closest('tr').children('.transferstat').html()
if($(this).prop('checked')) {
ischecked = true;
//alert(action);
// alert(statusvar);
// alert(transferstatusvar);
if (action == 'Recover'){
if (statusvar != 'OOS'){
// alert(statusvar);
isOKtoSubmit = false;
alertMessage = 'One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK';
}
}
if(isOKtoSubmit && ischecked !== false && action !== '--Select One--'){
$('#toolActions').submit();
}else {
alert(alertMessage);
}
});
If a user chooses Recover and chooses a record that has a status that is in 'OOS' they are getting the alert message in Chrome that the record does not have the correct status. In IE if you choose the same record the alert message does not appear and that would be correct.
When I use your code like this:
var action = 'Recover';
var statusvar = 'OOS';
if (action == 'Recover') {
if (statusvar != 'OOS') {
alert('One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK');
}
}
in both browsers it runs correctly. I think you have problem with your data.
In your original code try to use
alert(statusvar + ' - length:' + statusvar.length)
And check the character lenght of the variable. This way you can see if there is any funny character in your statusvar variable.

Execute Server Side from Client Side

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.

Categories

Resources