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);
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;
}
}
I want to bind a textbox with a field of DB by using JQuery Code, but I don't know what parameter I can use in AutoComplete function
<script type="text/javascript">
$(function () {
var availableTags = [??????];
$("#txtSearch").autocomplete({
source: availableTags });
});
behind code
public partial class MasterProfile : System.Web.UI.MasterPage
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
FindFriends();
}
void FindFriends()
{
SqlDataReader dr;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Select * From tblUser where UInfo Like #P1 and UID<> #P2 Order by UInfo";
cmd.Parameters.AddWithValue("#P1", "%" + txtSearch.Text + "%");
cmd.Parameters.AddWithValue("#P2", Convert.ToInt64(Session["ud"]));
cnn.Open();
dr = cmd.ExecuteReader();
txtSearch.Text = dr["UInfo"].ToString();
txtSearch.DataBind();
cnn.Close();
}
}
I have a jquery editable table.
In code behind there are three actions.
One to load data for datatable
Another to delete data from datatable
And the last one for Save data.
There is nothing special in these actions.
I have The problem with save data. Data are saved correctly to database and then there is redirection to load data to datable again.
When data are saved correctly do database, there is redirection which load new data to datatable and then i get this warning:
DataTables warning: table id=myDataTable - Requested unknown parameter '0' for row 8. For more information about this error, please see http://datatables.net/tn/4
I have looked this error on that page and i can not still find solution for this bug.
Interesting is when i get this error and i refresh page with datatable this time data are loaded correctly.
I do not know what is going on.
Please help
Here are two problematic actions
[HttpGet]
public ActionResult TesotwanieTabelki(int promotionId)
{
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionProductsViewModelItem =
new marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel();
promotionProductsViewModelItem.productDetails =
new List<marketPromocji.Areas.DELIVER.Models.ProductDetails>();
marketPromocji.Models.promocje promocje = unitOfWork.PromocjeRepository.GetByID(promotionId);
aspnet_Users produktyWDanejPromocji=promocje.promocje_produkty.Select(x => x.produkty).First().aspnet_Users; //czyje produkty w danej promocji
ICollection<produkty> produkty = unitOfWork.ProduktyRepository.Get().Where(x => x.aspnet_Users.UserId== produktyWDanejPromocji.UserId).ToList();
List<SelectListItem> selectList=new List<SelectListItem>();
foreach (produkty p in produkty)
{
selectList.Add(new SelectListItem { Text = p.nazwa, Value = p.id.ToString()});
}
promotionProductsViewModelItem.selectList = selectList;
promotionProductsViewModelItem.data_start = promocje.data_start;
promotionProductsViewModelItem.data_koniec = promocje.data_koniec;
promotionProductsViewModelItem.czy_zielony_koszyk = promocje.czy_zielony_koszyk;
promotionProductsViewModelItem.id = promocje.id;
promotionProductsViewModelItem.poziom_dostepnosci = promocje.poziom_dostepnosci;
promotionProductsViewModelItem.wynagrodzenie = promocje.wynagrodzenie;
if (promocje.sposob_wynagrodzenia != null)
{
promotionProductsViewModelItem.sposobWynagrodzenia = promocje.sposob_wynagrodzenia;
}
else
{
promotionProductsViewModelItem.sposobWynagrodzenia = "";
}
ICollection<marketPromocji.Models.promocje_produkty> promocje_produkty = unitOfWork.PromocjeProduktyRepository.Get().Where(x => x.ref_promocja == promotionId).ToList();
foreach (marketPromocji.Models.promocje_produkty item in promocje_produkty)
{
promotionProductsViewModelItem.productDetails.Add(new marketPromocji.Areas.DELIVER.Models.ProductDetails()
{
productId = item.produkty.id,
cena_brutto = item.cena_brutto,
cena_brutto_dla_sklepu = item.cena_brutto_dla_sklepu,
cena_netto = item.cena_netto,
cena_netto_dla_sklepu = item.cena_netto_dla_sklepu,
nazwa = item.produkty.nazwa,
url_obrazka = item.produkty.url_obrazka
});
}
Session[User.Identity.Name] = promotionProductsViewModelItem; //this session is used for datatable update action
return View(promotionProductsViewModelItem);
}
[HttpPost]
public ActionResult AddData(FormCollection formCollection)
{
int promotionId = Convert.ToInt32(formCollection.Get("promotionId"));
string addedProductId = formCollection.Get("Produkty");
int productId = Convert.ToInt32(addedProductId);
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionsProductsViewModel =
(marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel)Session[User.Identity.Name];
produkty produkt = new produkty();
produkt = unitOfWork.ProduktyRepository.GetByID(productId);
promocje_produkty promocjeProdukty = new promocje_produkty();
promocjeProdukty.cena_brutto = Convert.ToDecimal(formCollection.Get("cenaZakupuNetto")); //tutaj to jeszcze musze sprawdzic czy to w odpowiedniej kolejnosci jest;/
promocjeProdukty.cena_brutto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaZakupuBrutto"));
promocjeProdukty.cena_netto = Convert.ToDecimal(formCollection.Get("cenaSprzedazyNetto"));
promocjeProdukty.cena_netto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaSprzedazyBrutto"));
string zielonyKoszyk = formCollection.Get("zielonyKoszyk");
if(zielonyKoszyk==null)
{
promocjeProdukty.czy_zielony_koszyk = false;
}
else
{
promocjeProdukty.czy_zielony_koszyk = true;
}
promocjeProdukty.ref_produkt = productId;
promocjeProdukty.ref_promocja = promotionId;
try
{
unitOfWork.PromocjeProduktyRepository.Insert(promocjeProdukty);
unitOfWork.Save();
}
catch(Exception ex)
{
}
return RedirectToAction("TesotwanieTabelki", new { promotionId=promotionId});
}
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?