Asp.Net MessageBox and AnswerBox - javascript

I am new to Asp.Net.
I've found somewhere how to make in Asp.net/Javascript a MessageBox:
public static void Show(String str,Page pg, Object obj)
{
string s = "<SCRIPT language='javascript'>alert('" + str.Replace("\r\n", "\\n").Replace("'", "`") + "'); </SCRIPT>";
Type cstype = obj.GetType();
ClientScriptManager cs = pg.ClientScript;
cs.RegisterClientScriptBlock(cstype, s, s.ToString());
}
So the question is: is there a way (using a similar code) to get an answerBox (yes/No) displaying a message a getting the yes/No answer?
thanx in advance

Yes - use confirm instead of alert in your script. See for example http://www.w3schools.com/jsref/met_win_confirm.asp
Javascript example:
(function () {
var r = confirm("OK or Cancel ?");
if (r == true) {
alert("You pressed OK!");
} else {
alert("You pressed Cancel!");
}
})();

Related

How can i get the result of this javascript function and execute the proper stored procedure?

i have this insert form that lets the user insert the name of the server, if the server doesen´t exist it inserts, no problem and gives a javascript message confirming it was sucessful, but if the server already exist but as its _Active property = 0 it asks if he wants to activate it and what i want to do is if the user presses ok/yes it activates that server and if the user presses no it just reloads the page.ps:all the da. have there stored procedures well constructed.
protected void btn_insert_server_Click1(object sender, EventArgs e)
{
DataAccess da = new DataAccess();
DataTable dt = new DataTable();
string ServerName = ServerNameADD.Value.ToString();
if(ServerName.Length > 0)
{
dt = da.VerifyServer(ServerName);
if (dt.Rows.Count == 0)
{
da.Insert_Server(ServerName);
dt = da.GetServers();
gridServers.DataSource = dt;
gridServers.DataBind();
string message = "Servidor Inserido com sucesso.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
else
{
string message = "Servidor já existe. Deseja torna-lo ativo? .";
string script = "window.onload = function(){ ConfirmApproval('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "PopUp", script, true);
if (true)
{
da.UpdateServerToActive(ServerName);
string messageSuccUp = "Servidor atualizado com sucesso.";
string scriptSuccUp = "window.onload = function(){ alert('";
scriptSuccUp += messageSuccUp;
scriptSuccUp += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
else if(false)
{
da.GetServers();
}
}
}
}
Alright the way i was able to do this was, on front-end i created a onClientClick event called Confirm
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Este Servidor já existe, deseja ativa-lo?")) {
confirm_value.value = "Sim";
} else {
confirm_value.value = "Não";
}
document.forms[0].appendChild(confirm_value);
}
What it says is "This Server already exists, do you wish to activate it?" and gives a yes or no option.
On server-side since the onClick event is also triggered, it grabs the confirm_value (the yes or no answer) with that value it runs the if statment if its a confirmed yes value or if not it simply refreshes the gridView and the page itself.
This is inside the onClick button event
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Sim")
{
da.UpdateServerToActive(ServerName);
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Servidor Ativado')", true);
da.GetServers();
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Status do servidor mantidos')", true);
da.GetServers();
}

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?

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

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

Change Gridview Textbox's visible property true false on DropdownLists's Selected index change event using javascript not working

I am making Gridview's Textbox visible true or false when user changes Dropdownlists selectedIndexchange event for that i have done following code
My .CS File code is as below:
protected void gvTaskList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = (HiddenField)e.Row.FindControl("hdnStatus");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlStatus");
TextBox txt = (TextBox)e.Row.FindControl("txtVal");
if (ddl != null)
{
ddl.Items.Add("Not Started");
ddl.Items.Add("In Progress");
ddl.Items.Add("Complete");
if (hdn != null)
{
ddl.SelectedValue = hdn.Value;
}
//ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.Attributes.Add("onChange", "return myFun(" + "'" + txt.ClientID + "'" +");");
}
}
}
catch (Exception ex)
{
Utility.ErrorList("EmpTaskList--RowdataBound", ex.ToString());
}
}
Note: My combobox and textbox both are in EditTmplate
Javascript code is as below
<script type="text/javascript">
function myFun(txtControl) {
var v = document.getElementById("<%=" + txtControl + "%>");
alert(v);
}
When i m changing dropdownlist index function is called and alert is showing null.
So can anyone please suggest me what i m doing wrong??
I don't think you want the server-side tags in your getElementById call:
var v = document.getElementById(txtControl);

Categories

Resources