I am trying to create a login page that changes dynamically based on user attributes, specifically a username and role that is logged into a cookie. The login works fine; however, because I am using a really round-about way of calling C# functions, when my javascript method is called that contains the inline C# call, it skips all other lines of code in that method and goes right for the C# function.
I have read that a better way of going about this is the use of Webmethods and JQuery Ajax, however, I am unable to declare webmethods in my C# file.
My front end looks like the following
Login.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>PAM testing</title>
<link rel="stylesheet" type="text/css" href="Styles/Site.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="Scripts/JScript.js"></script>
</head>
<body>
<div id="banner">PAM Testing Tool</div>
<div id="content">
<form id="form1" runat="server" style="margin-left: 25%; text-align: center; height: 41px; width: 292px;">
<%--Login ASP Object--%>
<asp:Login ID="Login1" runat="server" onclick="process()"></asp:Login>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" style="text-align: center" ValidationGroup="Login1" />
</form>
<%--TEST AREA--%>
<script type="text/javascript">
function logCookie(){
document.cookie = "user=" + document.getElementById("Login1_UserName").value;// this is the id of username input field once displayed in the browser
}
function testFunction() {
<%=Login1_Authenticate() %>;
}
function process(){
logCookie();
testFunction();
}
</script>
</div>
</body>
</html>
My C# code looks like this
Login.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.EnterpriseServices;
public partial class Login : System.Web.UI.Page
{
int status;
int role;
SqlConnection conn;
SqlCommand command;
SqlDataReader reader;
protected string Login1_Authenticate()
{
// create an open connection
conn =
new SqlConnection("Data Source=xxx;"
+ "Initial Catalog=xxx;"
+ "User ID=xxx;Password=xxx");
conn.Open();
//string userName;
//userName = Convert.ToString(Console.ReadLine());
// create a SqlCommand object for this connection
command = conn.CreateCommand();
command.CommandText = "EXEC dbo.SP_CA_CHECK_USER #USER_ID = '"+Login1.UserName+"', #PASSWORD = '"+Login1.Password+"'";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
reader = command.ExecuteReader();
// display the results
while (reader.Read())
{
status = reader.GetInt32(0);
}
// close first reader
reader.Close();
//----------
existTest();
return "the login process is finished";
}
public static string GetData(int userid)
{
/*You can do database operations here if required*/
return "my userid is" + userid.ToString();
}
public string existTest()
{
if (status == 0)
{
//login
Session["userID"] = Login1.UserName;
command.CommandText = "EXEC dbo.SP_CA_RETURN_USER_ROLE #USER_ID = '" + Login1.UserName + "'";
reader = command.ExecuteReader();
while (reader.Read())
{
role = reader.GetInt32(0);
}
Session["roleID"] = role;
if (Session["userID"] != null)
{
string userID = (string)(Session["userID"]);
//string roleID = (string)(Session["roleID"]);
}
Response.Redirect("Home.aspx");
}
else
{
//wrong username/password
}
// close the connection
reader.Close();
conn.Close();
return "process complete";
}
}
Create your method as a web-service (web-api is good) then call it using jS ajax, here's an example i use with web-api and JS (this is posting data, use get if you have nothing to post)
$.ajax({
type: 'Post',
contentType: "application/json; charset=utf-8",
url: "//localhost:38093/api/Acc/", //method Name
data: JSON.stringify({ someVar: 'someValue', someOtherVar: 'someOtherValue'}),
dataType: 'json',
success: someFunction(), // callback above
error: function (msg) {
alert(msg.responsetext);
}
});
Related
I have jQuery to pull the autocomplete record as I type in the textbox, this data is being fetched using webservice. Now, everything works fine while using in Default.aspx page, but when I use this process from UserControl.ascx and call it in the default.aspx page then it doesn't return the autocomplete data (result).
WebService.asmx code:
[WebMethod]
public List<string> GetAutoCompleteData(string username)
{
string conString = ConfigurationManager.ConnectionStrings["MYCONNECTION"].ConnectionString;
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT SSName from SSRecord where SSName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["SSName "].ToString());
}
return result;
}
}
}
UserControl.ascx code:
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<link href="jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" class="autosuggest"></asp:TextBox>
Default.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/UserControl.ascx" TagPrefix="uc1" TagName="UserControl" %>
<body>
<form id="form1" runat="server">
<div>
<uc1: UserControl runat="server" ID="UserControl"/>
</div>
</form>
</body>
I got the similar post on the below link. Therefore, after some modification mentioned in the link I am able to sort this out.
https://www.aspsnippets.com/Articles/Implement-jQuery-Autocomplete-using-Web-Service-in-ASP.Net.aspx
I am trying to return my query as a user enters in information. However when I enter data into the textbox it returns an HTML popup page with random HTML code. I can figure out why the ajax callback isn't finding the [webmethod] as I think this may be the issue.
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>testing typescript</title>
<link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter- bootstrap/3.0.3/css/bootstrap.min.css'
media="screen" />
<script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<script type="text/javascript" src="http://cdn.rawgit.com/bassjobsen/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.min.js"></script>
<link rel="Stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" />
<script type="text/javascript">
$(function () {
$('[id*=txtSearch]').typeahead({
hint: true,
highlight: true,
minLength: 1
, source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("/Default.aspx.cs/GetCustomers") %>',
data: "{ 'prefix': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
items = [];
map = {};
$.each(data.d, function (i, item) {
var id = item.split('-')[1];
var name = item.split('-')[0];
map[name] = { id: id, name: name };
items.push(name);
});
response(items);
$(".dropdown-menu").css("height", "auto");
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
updater: function (item) {
$('[id*=hfCustomerId]').val(map[item].id);
return item;
}
});
});
</script>
</head>
<body>
Enter search term:
<form runat="server">
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control" autocomplete="off"
Width="300"/>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
</form>
</body>
</html>
Default.aspx.cs (code behind file)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit(object sender, EventArgs e)
{
string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);
}
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "<%$ ConnectionStrings:FormDataConnectionString %>";
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT [ID], [name], FROM [Wireless_Order] where ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["name"], sdr["ID"]));
}
}
conn.Close();
}
}
return customers.ToArray();
}
}
I have included this in my web.config file
<system.web>
<pages clientIDMode="Static"></pages>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
The issue was here.
/Default.aspx.cs/GetCustomers
Needed to be
Default.aspx/GetCustomers
to find the file.
Still get an error though when I click the backspace to clear the textfield.
Im using Microsoft Visual Studio 2012 as platform and i have created Web Forms Project
i have created data base file "SimpleDB.mdf" inside his "Table" folder i added new table called "Table" which has two columns - id and Name(string).What im trying is to insert string data into Name column of this table while calling server side function from javascript function.
This is the aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
and this is the aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
So basically im expecting when the button submit is clicked the Table Column "Name" will be filled with "Hello" but nothing happens and the column stays empty(NULL)
Table is reserved word in T-SQL so i would suggest you to use [] square brackets to enclose the Table.
Try This:
SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values('" + ID + "')", con);
Suggestion: Your query is open to sql injection attacks.I would suggest you to use Parameterised Queries to avoid them.
Try This:
using(SqlConnection con = new SqlConnection(source))
{
using(SqlCommand cmd = new SqlCommand("Insert into [Table](Name)
values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name",ID);
cmd.ExecuteNonQuery();
return "True";
}
}
I want to implement jquery textbox auto suggest in my c# asp.net application for the purpose of searching employees.Now i am using ajax auto suggest in my application but it's seems to be slow when data more than 50000 thousand.Somebody please help me.If any great idea about faster serching with huge data without using indexing please share with me.
jQuery Auto search details given bellow : Put down this code in your .aspx file. Here txtSearchBox is search box name.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel>
<ContentTemplate>
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" AutoCompleteType="Search"> </asp:TextBox>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
Now .cs file details:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=devserver;Initial Catalog=Catalog;Persist Security Info=True;User ID=userName;Password=Password"))
{
using (SqlCommand cmd = new SqlCommand("select (strEmployeeName + ',' + strEmployeeCode) as username from tblEmployee where strEmployeeName LIKE '%'+#SearchText+'%' ", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["username"].ToString());
}
return result;
}
}
}
}
If you wish you can use object data source like:In this case your object method should return List type data.
[WebMethod]
public static List<string> GetAutoCompleteData(string strSearchKey)
{
AutoSearch_BLL objAutoSearch_BLL = new AutoSearch_BLL();
List<string> result = new List<string>();
result = objAutoSearch_BLL.AutoSearchEmployeesData(strSearchKey);
return result;
}
jQuery UI provides a good autocomplete implementation and the docs suggest it can be used to pull autocomplete suggestions from very large databases
You can pull data in from a local and/or a remote source: Local is good for small data sets (like an address book with 50 entries), remote is necessary for big data sets, like a database with hundreds or millions of entries to select from.
http://jqueryui.com/demos/autocomplete/
Note that if you are returning 50K suggestions to the browser (as opposed to pulling suggestions from a pool of 50K possibilities), you are doing something wrong (that's a lot of data to push across the wire).
Implementing jQuery UI autocomplete would be simple as this
$(function(){
$( "#txtEmployee" ).autocomplete({
source: "employees.aspx",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
jQuery UI autocomplete supports some client side caching of the data. That will definitely improve the speed of search. Also, you may consider implementing a caching layer in your application where you store the List of Employees so that the autocomplete will not query your database everytime. Instead it will fetch the data from the caching layer.
I have to handle two callbacks in one page one on button event and other on List.
When button 'showDate' is clicked it display Time
and when button 'btnlookup' is clicked it show the respective value of listbox item.. below is my code HTML & .cs file
<head runat="server">
<title></title>
<script language="javascript">
function ReceiveResults(arg, context)
{
showDate.innerHTML = arg;
}
function LookUpStock() {
var lb = document.getElementById("ListBox1");
var product = lb.options[lb.selectedIndex].text;
CallServer2(product, "");
}
function ReceiveServerData(rValue) {
document.getElementById("ResultsSpan").innerHTML = rValue;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="showDate">aaa</span>
</br>
<input id="btnShowDate" type="button" value="getDate" onclick="CallServer();"/>
</div>
<div>
<asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
<br />
<br />
<button type="btnLookUP" onclick="LookUpStock()">Look Up Stock</button>
<br />
<br />
Items in stock: <span id="ResultsSpan" runat="server"></span>
<br />
</div>
</form>
</body>
Code for .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class callback : System.Web.UI.Page, ICallbackEventHandler
{
protected String returnValue;
protected String myDate;
protected System.Collections.Specialized.ListDictionary catalog;
public String GetCallbackResult()
{
//return returnValue;
return myDate;
}
public void RaiseCallbackEvent(String eventArgument)
{
myDate = System.DateTime.Now.ToLongTimeString();
//if (catalog[eventArgument] == null)
//{
// returnValue = "-1";
//}
//else
//{
// returnValue = catalog[eventArgument].ToString();
//}
}
protected void Page_Load(object sender, EventArgs e)
{
//For Time
ClientScriptManager cSM = Page.ClientScript;
String myCBRefrence = cSM.GetCallbackEventReference(this, "arg", "ReceiveResults", "context");
cSM.RegisterClientScriptBlock(this.GetType(), "CallServer", "function CallServer(arg, context) {" + myCBRefrence + ";}", true);
//callback back for listbox
//String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
//String callbackScript = "function CallServer2(arg, context){ " + cbReference + ";}";
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer2", callbackScript, true);
//catalog = new System.Collections.Specialized.ListDictionary();
//catalog.Add("monitor", 12);
//catalog.Add("laptop", 10);
//catalog.Add("keyboard", 23);
//catalog.Add("mouse", 17);
//ListBox1.DataSource = catalog;
//ListBox1.DataTextField = "key";
//ListBox1.DataBind();
}
}
Code which is comments is for the second callback event, Problem is in this code is that i can only raise one callback, can someone tell me what changes i need to make in code so that i can raise both callback event.
This is a piece of personal advice: do not write JavaScript in your C# code. This will get very messy and very hard to debug quickly.
If you really need to get this information, you should use an ASP.NET Web Service (a .asmx file). You can call these Web Services using JavaScript or jQuery (I prefer jQuery myself).
If I had a .asmx file like so:
[System.Web.Script.Services.ScriptService]
public class ServerTime : System.Web.Services.WebService
{
[WebMethod]
public string Get()
{
return System.DateTime.Now.ToLongTimeString();
}
}
I would call that using the following jQuery code:
$.ajax({ type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
url: "ServerTime.asmx/Get",
success: function (result) {
$("#showDate").html(result.d);
}
});
Note that success is deprecate din the latest version of jQuery, but I can't find a good example of done online.