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?
Related
I have a 2 drop down lists with company name and company addresses and a remove button linked to a stored procedure. Addresses is not being refreshed even though I am calling databind() on that address drop down List. Can anyone point me out in the right direction?
//Button to remove Company
protected void btnremovecompany_2(object sender, EventArgs e)
{
if (ddlcompanyaddress2.SelectedIndex != 0) /*checked to see if an address is Selected first*/
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")/* if yes is clicked then procedd to deactivate that company address*/
{
String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_update_company_active";
cmd.Parameters.Add("#companyname", SqlDbType.VarChar).Value = ddlcompany2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = ddlcompanyaddress2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#category", SqlDbType.VarChar).Value = ddlTrades2.SelectedItem.Text.Trim();
cmd.Connection = con;
**ddlcompanyaddress2.DataBind();**
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
/*Display message saying company is deactivated*/
string message = "Company has been removed";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
con.Close();
con.Dispose();
}
}
else
{
/*if canceled is clicked then display no changes*/
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No Changes were made!')", true);
}
}
else
{
string message = "Please pick an address first.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
}
You might be missing the datasource for your dropdown list. I am unable to find datasource in your code. You have just called databind method.
Can you please bind the datasource?
added this code to the try{} area and it resets all the dropdowns with fresh data.
ddlgettrades2();
getcompany2(ddlTrades2.SelectedItem.Text);
getaddress2(ddlcompany2.SelectedItem.Text);
How can i execute a C# method from JavaScript Code without refreshing the page?
this is the function that i want to execute:
protected void submitData(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
string worker = workerNameInput.Text;
string project = projectNameInput.Text;
string status = statusInput.Text;
string color = colorInput.Text;
if (worker.Equals("") || project.Equals("") || status.Equals("") || color.Equals(""))
return;
try
{
conn = new MySqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string com = "insert into " + table + " values ('" + worker + "','" + project + "','"+ status + "','"+ color + "');";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(com, conn);
string res = command.ExecuteNonQueryAsync().ToString();
Console.WriteLine(res);
Console.WriteLine("Insert command pass successfully");
}
catch (Exception ex)
{
Console.WriteLine("Failed to update database with \"insert\" command");
Console.WriteLine(ex.Message);
}
}
and i know that i should use
public partial class Home : System.Web.UI.Page, IPostBackEventHandler
and
public void RaisePostBackEvent(string eventArgument)
{
submitData(null, null);
}
inside the JS i used this code:
project.updateTable = function() {
var projectName = project.projectName();
var workerName = project.workerName();
var status = project.status();
var color = project.color();;
if (projectName == "" || workerName == "" || status == "" || color == "")
return;
project.rows.push({ projectName: ko.observable(projectName), workerName: ko.observable(workerName), status: ko.observable(status), color: ko.observable(color) });
project.projectName("");
project.workerName("");
project.status("");
project.color("");
var argumentString = projectName + "," + workerName + "," + status + "," + color;
var pageId = '<%= enterToDB.ClientID%>';
__doPostBack(pageId, argumentString);
};
This is how i configure my button:
<p><asp:Button runat="server" ID="enterToDB" Text="Add Project" data-bind="click: updateTable" onmouseover="this.style.background='orange', this.style.color='darkslateblue'" onmouseout="this.style.background='darkslateblue', this.style.color='orange'" /></p>
Can you correct my mistakes please?
and show me where i'm wrong?
You can use ASP.NET WebForm's UpdatePanel control to run the code-behind async. This is commonly known as "AJAX" (Asynchronous JavaScript and XML) or "XHR" (XML HTTP Request), and is built-in to the WebForms framework.
Here's a great resource on MSDN to get you started: https://msdn.microsoft.com/en-us/library/bb399001.aspx
It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.
Javascript to C#
-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }
-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />
C# to Javascript
-------C# code--------------------
object [] MyArgs = { "Hello" } ; WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;
-------Javascript----------------
function MyJsFunction(s) { alert(s) ; }
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!");
}
})();
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).
I have a hidden variable in my .aspx page.
input type="hidden" runat="server" id="isdup"
Now in code behind i check for certain conditions and assign isdup a value accordingly. However, this may not help you much but this is what i do in code behind.
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Now I need to access the isdup inside javascript. However the problem has been that those values are not passed and isdup is null.
var showus= document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
if(showus == "true")
{
Showduplicate();
}
So, kindly let me know the mistake i have been doing?
Hve you tried with:
var showus= document.getElementById('<%=isdup.ClientID %>').value;
update
is javascript at the end of the page?
update
try to put this code in the page:
<asp:HiddenField ID="isdup" runat="server" Value="eee"/>
<script>
var showus = document.getElementById("<%=isdup.ClientID %>").value;
alert(showus);
</script>
this works for me!
update
in page_load...
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
my example:
protected void pagesTree_NodeClick(object sender, RadTreeNodeEventArgs e)
{
PageStructure page = pageService.GetPage(Guid.Parse(e.Node.Value));
this.LoadPageData(page);
isdup.Value = "xxx";
}
update
bool exist = (from n in mCDC.NCDCPoints
where n.EVENT_TYPE_ID == eventID
where n.BeginDate == begin
where n.EndDate == end
select n).Count() > 0;
if (!ClientScript.IsStartupScriptRegistered("clientscript"))
{
string script1 = "<script language=JavaScript>";
script1 += "var showus= document.getElementById('" + isdup.ClientID + "').value;";
script1 += "alert(showus);";
script1 += "</script>";
ClientScript.RegisterStartupScript(typeof(Page), "clientscript", script1);
}
try
{
if (!exist)
{
//do this before insert so the insert will have correct values
isdup.Value = "false";
SaveAllColumnFields(ref ncdc, e);
mCDC.NCDCPoints.InsertOnSubmit(ncdc);
mCDC.SubmitChanges();
//do this after insert because it wont work until the ncdc object
//has been assigned an ID
SaveAllDynamicFields(mCDC, ref ncdc, e);
mCDC.SubmitChanges();
Grid1.CurrentPageIndex = 0;
}
else
{
isdup.Value = "true";
System.Windows.Forms.MessageBox.Show(isdup.Value);
}
Try this JQuery code.
var showus= $("#<%=isdup.ClientID %>").val();
Replace your input field and try this with jquery code
UPDATED
<asp:HiddenField ID="isdup" runat="server" EnableViewState="true" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"/>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var showus = $("#<%=isdup.ClientID %>").val();
alert(showus);
if (showus == "true") {
Showduplicate();
}
});
</script>