Get data from database without refreshing the page in ASP.NET - c#

I'm doing a project in ASP.net and with SQL Server. I'm calling a stored procedure on user login screen to authenticate the user. But when I call the stored procedure, the entire page needs to be refreshed in order to get the data.
How can I achieve the same without refreshing the page?
This is my current code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}

Use Ajax Extension, Here is the quick example:
.aspx File
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" id="username" name="username" placeholder="Enter Username"></asp:TextBox>
<asp:TextBox name="passwd" ID="passwd" runat="server" placeholder="Enter Password"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
<br />
<asp:Label ID="LblError" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs File - add this to Click event of Login Button
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "";
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
string User = username.Text;
string Pwd = passwd.Text;
//cn = "<< your connection string>>";
try
{
cn.Open();
// Your code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '" + Pwd + "'";
cmd = new SqlCommand(sql, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
catch (Exception exce)
{
LblError.Text = exce.Message;
}
finally
{
cn.Close();
}
}
You can find UpdatePanel and ScriptManager under Toolbox -> Ajax Extension
Use try-catch block to handle runtime exceptions.

Based on the code you have, in Web Forms you can:
use an Update Panel;
or Page/Web Method
or a simple(r) Web handler (ashx)

If you want to load the data without refreshing the page. you can expose webservice method or create page method then you can call ASP.NET page method through ajax
[WebMethod]
public static string Insert_Data(string user, string pwd)
{
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
Client Side
$(document).ready(function () {
$('#btnsubmit').click(function () {
var name = $('#user').val();
var sex = $('#pwd').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Insert_Data',
data: "{'user':'" + user+ "','pwd':'" + pwd + "'}",
async: false,
success: function (response) {
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
});
});

There are 3 possible ways I know of:
1) using update panel:
see example: http://www.aspdotnet-pools.com/2014/07/ajax-login-form-in-aspnet-using-cnet.html
2) using webmethod:
see example: http://www.aspforums.net/Threads/133296/Develop-simple-AJAX-Login-form-using-jQuery-in-ASPNet/
3) using tiered coding:
see example: https://www.codeproject.com/Articles/170882/jQuery-AJAX-and-HttpHandlers-in-ASP-NET
I prefer method 3 coding as it is more flexible and the tiered coding concept is portable to other web programming platform.

Related

how to do Log IN with current User in the masterpage

how can i do a login with current user? the current user will be displayed in the masterpage of the default homepage and the label from the masterpage will inherit to the content pages of the master page.
here is my login page asp code:
<div class="container-fluid">
<form class="form-signin" runat="server">
<h1 class="form-signin-heading text-muted">Sign In</h1>
<asp:TextBox ID ="email" runat="server" CssClass="form-control" placeholder="Email Address"></asp:TextBox>
<asp:TextBox ID ="password" runat="server" CssClass="form-control" placeholder="Password" TextMode="Password"></asp:TextBox>
<br />
<asp:Button ID="btnLogIN" runat="server" CssClass="btn btn-primary btn-block" Text="Log In" OnClick="btnLogIN_Click" />
</form>
and my aspx.cs code is here and i dont know if this is correct.
protected void btnLogIN_Click(object sender, EventArgs e)
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
SqlDataReader reader = null;
int empid = 0;
string dbuser = "";
string dbpword = "";
string username = email.Text;
string passwords = password.Text;
string login = "Select * from MOSEFAccount where UserName = '" + username + "' AND Password = '" + passwords + "'";
try
{
connUser.Open();
read.CommandText = login;
reader = read.ExecuteReader();
}
catch
{
Console.WriteLine("Error");
}
while (reader.Read())
{
empid = reader.GetInt32(0);
dbuser = reader.GetString(1);
dbpword = reader.GetString(2);
}
if (username == dbuser && passwords == dbpword)
{
Response.Redirect("~/Default.aspx?ID=" + empid);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type ='text/javascript'>");
sb.Append("alert('Invalid Account');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}
connUser.Close();
}
Can you elaborate on the meaning of current user? Unless you login you are not logged in user but anonymous user.
Update:
Store the pulled data in Session object and access it anytime whenever and wherever you like. For example:
For storing details use:-
if (username == dbuser && passwords == dbpword)
{
Session["UserName"] = username;
Session["EmpId"] = empid;
Response.Redirect("~/Default.aspx?ID=" + empid);
}
For displaying use (in the master page):
<%=Session["UserName"]%>
<%=Session["EmpId"]%>
You can build upon this like creating a User class and then creating an instance of this class and storing the instance itself in Session.

Checking the availability of a username in asp.net using ajax

I am having following textbox in my aasp.net page. And user enters any username in it and I want ajax to check the availability and show the success or failure message in the label as the user leaves the text box.
UserName<asp:Label ID="usernamelbl" runat="server"></asp:Label>
<asp:TextBox ID ="usernametxt" runat="server" CssClass="twitterStyleTextbox"></asp:TextBox><br />
thats how I am using the ajax
function result() {
var username = "<%=usernametxt%>";
var result = "<%usernamelbl%>";// here i am getting an error on usernamelbl
var jsonText = JSON.stringify({ list: username });
//array = +jsonText;
$.ajax({
url: "staffregistration.aspx/Test", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonText,
success: function (data) {
if (data == username) {
result = "username available"
}
else {
result = "username not avilable"
}},
error: function () { alert("its not working"); }
});
return false;
}
and thats how i am interacting with the aspx
public static string Test(string username)
{
string conString = #"user id=ejaz;password=ejaz;persistsecurityinfo=True;server=localhost;database=geospatialdb";
MySqlConnection conn = new MySqlConnection(conString);
MySqlDataReader reader = null;
conn.Open();
MySqlCommand command = new MySqlCommand("select owner_id from owner where owner_username = '" + usernametxt.Text + "';", conn);
reader = command.ExecuteReader();
username = reader[0].ToString();
return username;
}
Here is how you can detect the change in usernametxt using JavaScript through onChange event and Ajax using WebMethods.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="usernameupdatepanel">
<ContentTemplate>
UserName <asp:Label ID="usernamelbl" runat="server"></asp:Label>
<asp:TextBox ID ="usernametxt"
runat="server" CssClass="twitterStyleTextbox"
OnChange="CheckUserName(this)" ></asp:TextBox><br />
</ContentTemplate>
</asp:UpdatePanel>
JavaScript:
function CheckUserName(oName)
{
PageMethods.UserNameChecker(oName.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=usernamelbl.ClientID %>');
if (methodName == "UserNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'username not available';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = 'username available';
lbl.style.color = "green";
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool UserNameChecker(string newUserName)
{
string conString = #"user id=ejaz;password=ejaz;persistsecurityinfo=True;server=localhost;database=geospatialdb";
MySqlConnection conn = new MySqlConnection(conString);
MySqlDataReader reader = null;
conn.Open();
MySqlCommand command = new MySqlCommand("select owner_id from owner where owner_username = '" + newUserName + "';", conn);
object found = command.ExecuteScalar();
if (found != null)
return true;
else
return false;
}
In a more simple way, just add the scriptmangaer tag and the update panel, then you add the textbox.
Note: Don't forget to set autopostback to true and add an event i.e OnTextChanged event and its handler
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="Email" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The event handler
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//your logic
}

binding data in asp c# like php, is that possible?

I am new to asp.net, and what I want to know is how to bind data directly into a custom div
without using things such as data grid or any other thing, let's say I want to bind a description for something stored in my sql DB.
In PHP i used to do this:
<p>
<?php echo $row_RecordSetName['col']; ?>
</p>
But how to do in asp.net using C# in a webform?
I tried to do it in a dataset thing like so but it keeps giving errors:
<p>
<%= Dataset.DB[0].colNAME.ToString() %>
</p>
as well as i tried doing the following stupid way :
try
{
for (int i = 1; i < 7; i++)
{
SqlConnection cn = new SqlConnection("Data Source=server;Initial Catalog=db;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM mallsdb where mall_un='" + i + "'", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
MallsDS tds = new MallsDS();
da.Fill(tds, tds.Tables[0].TableName);
string MallPIC = Convert.ToString(tds.mallsdb[0].mall_pic);
string MallNAME = Convert.ToString(tds.mallsdb[0].mall_name);
string MallUn = Convert.ToString(tds.mallsdb[0].mall_un);
string MallDESP;
string check_desp = Convert.ToString(tds.mallsdb[0].mall_desp);
if (check_desp.Length < 50)
{
MallDESP = check_desp;
}
else
{
string under = check_desp.Substring(0, 30);
MallDESP = under + "....";
}
Result[i] = "<div class='malls'>" + "<img src='images/" + MallPIC + "' width='250' height='250' />" + "<a class='namer' href='malls_private.aspx?mall_un=" + MallUn + "'><h1>" + MallNAME + "</h1></a><p>" + MallDESP + "</p></div>";
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
Label1.Text = Result[1];
Label2.Text = Result[2];
Label3.Text = Result[3];
Label4.Text = Result[4];
Label5.Text = Result[5];
Label6.Text = Result[6];
In C#, you can do something like <div runat='server' id='divWhateverDiv'> in the aspx and then in the actual C# code (not in the aspx itself) you can reference the div element as a normal C# variable by its id, and do something like divWhateverDiv.innerHTML = "whatever"; Visual Studio's intellisense will help you with the actual capitialization of the members and such. What you're trying to do is more like old asp than asp.net
thanks friends and in the following is the answer to my question, as i read about it in microsoft MSDN.
<%# Page language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection cnn = new
SqlConnection("server=(local);database=pubs;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "authors");
Repeater1.DataSource = ds.Tables["authors"];
Repeater1.DataBind();
}
</script>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>

Retrieve Sql Data Using WebMethod & Jquery

I wants to retrieve data from sql server using webserver/jquery and I read many articles but not getting the require matters except below but I think It's support FrameWork .Net 3.5 not 2.0. And I have the same requirement to use it in ASP.Net 2.0.
//On WebServer Page..
WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class test : System.Web.Services.WebService
{
[WebMethod]
public string GetCustomer(string memberID)
{
string response = "<p>No customer selected</p>";
string connect = "Server=myserver;Initial Catalog=mydatabase;uid=myuser;pwd=mypassword";
string query = "SELECT name, father, mother from samaj where name=#memberID";
if (memberID != null)
{
StringBuilder sb = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("memberID", memberID);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
sb.Append("<p>");
sb.Append("<strong>" + rdr["name"].ToString() + "</strong><br />");
sb.Append(rdr["father"].ToString() + "<br />");
sb.Append(rdr["mother"].ToString() + "<br />");
response = sb.ToString();
}
}
}
}
}
return response;
}
}
}
//.aspx page...
<script type="text/javascript" src="jquery-1.3.2.min.js" ></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#Customers").change(function()
{
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.asmx/GetCustomer",
data: "{ memberID: '" + $('#Customers').val() + "'}",
dataType: "json",
success: function(data)
{
$("#CustomerDetails").html(data.d);
}
});
});
});
</script>
<form id="form1" runat="server">
<div id="SelectCustomers">
<asp:DropDownList ID="Customers" runat="server">
</asp:DropDownList>
</div>
<div id="CustomerDetails">
</div>
</form>
The DropdownList Binding In Default.aspx.cs page...
protected void Page_Load(object sender, EventArgs e)
{
string connect = "Server=myserver;Initial Catalog=mydatabse;uid=myuser;pwd=mypwd
string query = "SELECT name FROM samaj";
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
Customers.DataSource = cmd.ExecuteReader();
Customers.DataValueField = "name";
Customers.DataBind();
}
}
.asmx page testing ok It’s retrieves the data well but on client side It’s not return any data. How to achieve it in ASP.Net 2.0?.

Add button to webpage via code behind in asp.net and delete dynamic db entrys

Hi im wondering if its possible to add a asp button to the code below, the code below adds an image and text from my database to a dynamic div on my asp page:
using System.Data.Odbc;
using System.IO;
public partial class UserProfileWall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
PopulateWallPosts(theUserId);
}
private void PopulateWallPosts(string userId)
{
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
//("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
using (OdbcDataReader reader = cmd.ExecuteReader())
{
test1.Controls.Clear();
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
//div.Style["float"] = "left";
div.ID = "test";
Image img = new Image();
img.ImageUrl = String.Format("{0}", reader.GetString(1));
// this line needs to be represented in sql syntax
//img.ImageUrl = "~/userdata/2/uploadedimage/batman-for-facebook.jpg";
img.AlternateText = "Test image";
div.Controls.Add(img);
div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp "+"{0}", reader.GetString(0))));
div.Style["clear"] = "both";
test1.Controls.Add(div);
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(theUserId);
}
}
Here is the strange thing tho, if I do manage to add a button similar to the way I have added an image, how would I call that button, for example:
I want to call this button "delete" and add code to delete the text in my database related to that div, but if there is multiple divs(there all named the same div id=test) with text and they all have the same asp button how would I be able to tell the button to only delete the current text(in the db) for the current div??
My database stores the information like so:
Im thinking I would have to use idwallposting but not sure how?
Also to give a visual representation of how it looks it may help aid in the understanding:
My css and asp:
div#test1 {
}
div .test {
width:90%;
z-index:1;
padding:27.5px;
border-top: thin solid #736F6E;
border-bottom: thin solid #736F6E;
color:#ffffff;
margin:0 auto;
white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
word-wrap: break-word;
}
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<p>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"
Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px"
onclick="Button1_Click" />
</p>
<p>
</p>
<style type="text/css">
img {border-width:0px; width:100px; height:100px;}
</style>
<div id="test1" runat="server" />
</div>
</asp:Content>
Why not give each div a unique ID like div.ID = "test" + idWallPostings; ?
It is not a good idea to have non-unique IDs for any element.
Regarding your main problem, why not use one of the templated data controls like Repeater or ListView and add a Command handler. Then in the template add the button with a command argument for the current data item's data key.
see: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemcommand.aspx
You can see how the the button is used to carry additional information in its click event:
<asp:LinkButton runat="server"
ID="SelectEmployeeButton"
Text="Add To List"
CommandName="AddToList"
CommandArgument='<%#Eval("LastName") + ", " + Eval("FirstName") %>' />
and how it is retrieved and used (it is accessed using e.CommandArgument):
protected void EmployeesListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "AddToList"))
{
// Verify that the employee ID is not already in the list. If not, add the
// employee to the list.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
string employeeID =
EmployeesListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
if (SelectedEmployeesListBox.Items.FindByValue(employeeID) == null)
{
ListItem item = new ListItem(e.CommandArgument.ToString(), employeeID);
SelectedEmployeesListBox.Items.Add(item);
}
}
}
For deletion from database with C# in Visual Studio 2008 ASP.net write the following code by double-clicking on button:
protected void btndel_Click(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand cmd;
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\THEGIRL\\Documents\\Visual Studio 2008\\WebSites\\WebSite72\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
conn.Open();
cmd = new SqlCommand("Delete from logintable where username='"+txtdeluname.Text+"'",conn);
lbldel.Text = "Record is deleted";
cmd.ExecuteNonQuery();
conn.Close();
}

Categories

Resources