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);
Related
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();
}
So here is the deal I am working on a simple project, with a log in form and a sign up form. In the beginning you will see this which is displayed in the picture.
After you sign up or log in, then you will get what is displayed in the picture below
When I click on a new page for example: like on the home page, videos, contact, then it will just return back to its original state in the first picture. I want to prevent that and keep it the way it is in the second picture until you click on log out. I have been looking everywhere for answers and can't seem to find exactly what I am looking for.
Here is a little code from what I have used to try and accomplish this
HTML code, which is located in the master page
<a id ="LogIn" runat="server" href="../LogIn.aspx">Log In:</a>
<a id ="SignUp" runat="server" href="../SignUp.aspx">Sign Up:</a>
<a id ="LogOut" href="../LogIn.aspx">Log Out:</a>
CSS code in the master page as well.
#LogIn
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 767px;
}
#SignUp
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 867px;
}
#LogOut
{
margin-top: 30px;
font-size: 20px;
position: absolute;
margin-left: 880px;
display: none;
}
Okay I have tried doing it in javascript, which is in the master page
function showAlert() {
$(".SignUp").slideUp("25000");
$(".LogIn").slideUp("25000");
$(".CreateAccount").hide();
$(".AccountLogIn").hide();
$("h1").remove();
$("#LogIn").remove();
$("#SignUp").remove();
$("#LogOut").show();
}
the showalert function is being called from the button click event in C# for the LogIn form and SignUp form
SqlConnection connection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=**************";
connection.Open();
}
public void CheckEmail()
{
SqlCommand Comm = new SqlCommand("select count(*) from SignUp where Email ='" + Email.Text + "'", connection);
Comm.Parameters.AddWithValue("#Email", Email.Text);
Comm.Connection = connection;
int count = Convert.ToInt32(Comm.ExecuteScalar());
if (count > 0)
{
Thread.Sleep(3000);
VerifyEmail.Visible = true;
}
else
{
Thread.Sleep(5000);
InsertData();
VerifyEmail.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
}
}
public void InsertData()
{
SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(#FirstName, #LastName, #Password, #Email)", connection);
Command.Parameters.AddWithValue("#FirstName", FirstName.Text);
Command.Parameters.AddWithValue("#LastName", LastName.Text);
Command.Parameters.AddWithValue("#Password", Password.Text);
Command.Parameters.AddWithValue("#Email", Email.Text);
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
LogIn.Visible = false;
SignUp.Visible = false;
Command.ExecuteNonQuery();
}
protected void SignUp_Click(object sender, EventArgs e)
{
CheckEmail();
connection.Close();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert()", true);
//Response.Write("<script language=JavaScript> alert('You have Successfully created an Account'); </script>");
//Response.Redirect("~//Default.aspx");
}
I also tried doing it in the back end code as well shown above. It also shows how the user is being loged in and saved in the database. That is being called in the button click event, when you click to create an account or click to log into an account.
LogIn.aspx.cs
SqlConnection conn = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
conn.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=*******";
conn.Open();
}
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
public void ExecuteLogIn()
{
SqlCommand Command = new SqlCommand("select ISNULL(Email, '') As Email, ISNULL(Password, '') As Password from SignUp where Email='" + Email.Text + "'", conn);
SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= #FirstName", conn);
Command2.Parameters.AddWithValue("#FirsName", FirstName.Text);
SqlDataReader dr = Command.ExecuteReader();
string UserEmail = Email.Text;
string UserPassword = Password.Text;
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
while (dr.Read())
{
if (this.CompareStrings(dr["Email"].ToString(), UserEmail) &&
this.CompareStrings(dr["Password"].ToString(), UserPassword))
{
InvalidLogIn.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
//LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
LogIn.Visible = false;
SignUp.Visible = false;
}
else
{
InvalidLogIn.Visible = true;
}
}
//Command.Parameters.AddWithValue("#Password", Password.Text);
//Command.Parameters.AddWithValue("#Email", Email.Text);
conn.Close();
}
protected void LogIn_Click(object sender, EventArgs e)
{
ExecuteLogIn();
}
Any help would be greatly appreciated thanks so much
The code is missing too many pieces. I could only give you a direction. If you have specific question about FormAuthentication, please create a new question.
CheckEmail method is prone to SQL Injection attack. You want to consider using Parameterized Query.
We normally need both username*(or email)* and password to validate an account. Easiest way to implement authentication in ASP.NET Web Form is to use FormAuthentication.
The following is the sample code. I also created a sample project at GitHub, so that you can test it.
Sign-In method inside Login.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
string username = UsernameTextBox.Text,
password = PasswordTextBox.Text;
bool rememberMe = RememberMeCheckBox.Checked;
// Retrieve username and hashed password from database, and validate them
if (username.Equals("johndoe", StringComparison.InvariantCultureIgnoreCase) &&
password.Equals("123456", StringComparison.InvariantCultureIgnoreCase))
{
FormsAuthentication.RedirectFromLoginPage(username, rememberMe);
}
MessageLabel.Text = "Invalid username or password";
}
Global.asax.cs
We then retrieve username from cookie, and save it in Principal Object.
public class Global : HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (decryptedCookie != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
}
web.config
Please ensure authentication tag is in web.config.
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
Usage
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
}
}
With this code I show JavaScript alert message box in ASP.Net from server side using C#.
But I need show the message only on first access to the web page, how to do resolve this ?
Please help me.
My code below, thank you in advance.
protected void Page_Load(object sender, EventArgs e)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
You need to check that the page is not posting back before you display your alert:
if (!IsPostBack)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Updates:
You can create a cookie to track the alert so it does not display after displaying during the initial page load:
private bool Alerted()
{
if (Request.Cookies["alerted"] != null)
return Server.HtmlEncode(Request.Cookies["alerted"].Value) == "true";
else
{
Response.Cookies["alerted"].Value = "true";
Response.Cookies["alerted"].Expires = DateTime.Now.AddDays(10);
return false;
}
}
Usage:
if(!Alerted())
{
// alert script here
}
I have created a dynamic menu as user control and it is working fine in a test application.But when i integrated in to the live application child menu items will come only if i click parent menu item rather if you hover over menu no child items ie while page load or postback child items are not coming when i used browser developer tools console window an error is coming whenever pageload or postback which is like shown below
SCRIPT1004: Expected ';'
Default.aspx, line 728 character 24
page can be varied so here it is Default.aspx
and the code which i am using for dynamic menu is
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData(0);
PopulateMenu(dt, 0, null);
}
}
private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem
{
Value = row["MENUID"].ToString(),
Text = row["MENUNAME"].ToString(),
NavigateUrl = row["URL"].ToString(),
Selected = row["URL"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
};
if (parentMenuId == 0)
{
dynamicMenu.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
//dynamicMenu.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
}
}
private DataTable GetData(int parentMenuId)
{
string query = "SELECT MENUID, MENUNAME, ACTIVE, URL,APPLICATION_ID FROM MENUS_APPS WHERE PARENTID = :ParentMenuId AND APPLICATION_ID ='" + Global.GetApplicationId() + "' and ACTIVE='Y' and ROLE_ID = 1";
string constr = ConfigurationManager.ConnectionStrings["UserConnections"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
DataTable dt = new DataTable();
using (OracleCommand cmd = new OracleCommand(query))
{
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Parameters.AddWithValue(":ParentMenuId", parentMenuId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
Any idea why i am getting like this??
Anything to check in web.config??
I am trying to update database while user closing browser/tap.I tried with onbeforeunload function and its working fine but even in page refreshing.Here is code what i tried
MyJSP :
<script type="text/javascript">
var refresh=false;
$(window).keydown(function(event){
if(event.keyCode==116)
{
refresh=true;
}
})
$(window).on('beforeunload', function(){
if(refresh==false)
{
$.get("BrowserCloseServlet", function() {
});
}
});
</script>
MyServlet :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
#SuppressWarnings("unused")
String getId = request.getParameter("getid");
Connection con = null;
PreparedStatement pst = null;
PreparedStatement pst2 = null;
ResultSet rst = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5", "root", "");
String query = "select NoOfCount from tbl_BroserCloseTable ";
String query2 = "update tbl_BroserCloseTable set NoOfCount= ? where Sno= ?";
// Statement st = con.createStatement();
// st.executeUpdate("");
pst = con.prepareStatement(query);
rst = pst.executeQuery(query);
if (rst.next()) {
int count = rst.getInt(1);
System.out.println("Actuall count is :" + count);
count -= 1;
pst2 = con.prepareStatement(query2);
pst2.setInt(1, count);
pst2.setInt(2, 1);
pst2.executeUpdate();
System.out.println("Updated successfully...");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
con.close();
rst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Its working fine(not update DB while click f5 button) but if the user click on refresh button then that servlet page called and updated DB.I want to stop calling onbeforeunload when click on refresh button in browser.
Update :
I only want to know how make that refresh=false; while click on refresh button in browser.
How to do this one?