In your current code, you make a call to the database for each and every keystroke.
This is not very efficient or user friendly due to many reasons.
You would be better off splitting up the code into two parts.
Part 1
This part should be executed when the page is loaded or something similar.
In any case, you want to do this operation as few times as possible.
Declare a new member variable
private DataTable dtInvoices = null;
Then add a method that is called every time you want to update the invoices
public void GetInvoices()
{
string connstring = "Data Source=.;Initial Catalog=Accounts;Integrated Security=True";
string query = "select InvoiceNo from AccountSummary";
using (SqlConnection conn = new SqlConnection(connstring))
{
SqlCommand cmd = new SqlCommand(query, conn);
dtInvoices = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtInvoices);
}
}
Instead of a DataTable you could of course use a
List<string> invoiceNumbers
.
Then modify your existing method
public bool IsInvoiceExists(string invoicenumber)
{
if (dtInvoices == null)
return false;
bool exists = (dtInvoices.Select(string.Format("InvoiceNo = '{0}'", invoicenumber)).FirstOrDefault() != null);
return exists;
}
No idea how this code is connected to anything else in your code snippet.
bool isExist;
isExist = db.Users.Any(u => u.Name == userName);
return Json(isExist);
[UPDATE]
Due to comment
Maybe you should try to make it a public property in the controller.
private DataTable dtInvoices = null;
public DataTable Invoices
{
get
{
return dtInvoices;
}
set
{
dtInvoices = value;
}
}