Insert Data into SQL table using Javascript and ASP.NET - c#

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";
}
}

Related

GETTING ERROR IN SIGN UP PAGE for inserting values in SQL server DATABASE table through webform TEXTBOX

hi I am trying to make a log in page as well as sign up page in asp.net using 3 tier architecture by using sql server architecture. I am able to fetch data from sql server data base which I have manually inserted during table creation in database and I am able to use it in my log in page.
I have also created a sign up page but I am not able to get the values from sign up webform textbox to sqlserver database I am getting some error kindly help me with this.
I have given the connection string of sql server in web.config
my sql server table creation code
CREATE TABLE LOGINDETAILS
(USERID VARCHAR(50),
PASSWORD VARCHAR (50)
);
INSERT INTO LOGINDETAILS (USERID,PASSWORD) values( 'sam', 'pass');
web.config connection string code
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="DBcon" connectionString="Data Source=P3A-B1YH882\SQLSERVER;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
my business layer /middle layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using DataAcess;
using System.Data.SqlClient;
using System.Data.Sql;
namespace middlelayer
{
public class UserBO
{
private string _UserName = " ";
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password = " ";
public string Password
{
get { return _Password; }
set { _Password = value; }
}
DataA da = new DataA();
public bool getUser()
{
if (da.IsValid(UserName, Password).Tables[0].Rows.Count == 0)
{
return false;
}
else
{
return true;
}
}
}
}
my datAccess layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace DataAcess
{
public class DataA
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
public DataSet IsValid(string UserName, string Password)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM LOGINDETAILS WHERE USERID ='" + UserName + "' and PASSWORD= '" + Password + "'", con);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
return ds;
}
}
}
MY LOGIN PAGE CODE
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApplication4.login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 277px">
<form id="form1" runat="server">
<div>
<asp:Label ID="lbluserid" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Height="17px" Text="User ID" Width="52px"></asp:Label>
<asp:TextBox ID="txtuserid" runat="server" BackColor="#99FFCC" style="margin-left: 122px"></asp:TextBox>
<br />
</div>
<p>
<asp:Label ID="lblpassword" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Text="Password"></asp:Label>
<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" BackColor="#99FFCC" style="margin-left: 110px" ></asp:TextBox>
</p>
<p>
</p>
<asp:Button ID="btnlogin" runat="server" BackColor="#33CCFF" BorderStyle="Ridge" OnClick="btnlogin_Click" style="margin-left: 78px" Text="Login" Width="107px" />
<p>
</p>
<asp:Label ID="Label1" runat="server" Text="NOT REGISTERED ??"></asp:Label>
<asp:HyperLink ID="HyperLink1" runat="server" BorderStyle="Outset" NavigateUrl="~/sign_up.aspx">SIGN UP</asp:HyperLink>
</form>
</body>
</html>
* MY SIGN UP PAGE CODE*
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="sign_up.aspx.cs" Inherits="WebApplication4.sign_up" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="lblssignup" runat="server" BackColor="#FF99CC" Text="SIGN UP"></asp:Label>
<br />
<br />
<p>
<asp:Label ID="lblsuserid" runat="server" Text="ENTER USER ID"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" style="margin-bottom: 0px"></asp:TextBox>
</p>
<asp:Label ID="lblspassword" runat="server" Text="ENTER PASSWORD"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="66px" />
</p>
</form>
</body>
</html>
SIGN UP PAGE BUTTON CODE FOR ENTERING DATA INTO SQL SERVER DATABASE ON BUTTON CLICK
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using middlelayer;
namespace WebApplication4
{
public partial class sign_up : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES ('" +TextBox1.Text+ "' , '" +TextBox2.Text+ "')";
SqlCommand com = new SqlCommand(ins,con);
DataSet du = new DataSet();
SqlDataAdapter sdi = new SqlDataAdapter(com);
sdi.Fill(du);
con.Close();
}
}
}
I AM getting error in this last code only of sign up button it is not able to insert values of SIGN UP webform Textbox to sql server databse table and also not reflecting the real values which I want to add in sql server TABLE using sign up webform and also noty saving it. It is sending some error values . kindly help me with this.
BELOW ARE THE IMAGES OF LOG IN AS WELL AS SIGN UP PAGE FOR REFERENCE
LOGIN PAGE WEB FORM
SIGN UP PAGE WEBFORM
KINDLY HELP IN RESOLVING THIS ISSUE
Try this:
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES (#param1 , #param2)";
SqlCommand cmd = new SqlCommand(ins,con);
cmd.Parameters.Add("#param1", SqlDbType.Varchar, 50).value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = TextBox2.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close()

The name 'UName' does not exist in the current context

When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.
So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!

AutoCompleteExtender on TextBox returns the page HTML

I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}

Call C# Method with JS

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);
}
});

C# User interface when uploading excel spreadsheet to SQL Database via VS 2005

currently I have a web which loads excel spreadsheet data into SQL database. When the page loads, all the parameters are hard coded on the code behind, so I do not have 'browse for file' and 'upload' button. I would like to implement these 2 buttons but I am not sure how should I do it.
I am using C# language, Visual Studio 2005 and SQL Server 2005.
Below is the code which runs the import of excel data into the database:
importexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class ImportExcel : System.Web.UI.Page
{
public static string path = #"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand
("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tStudent";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
Below is my code for the my current html:
importexcel.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ImportExcel.aspx.cs" Inherits="ImportExcel" %>
<!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></title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
Please select a Excel spreadsheet to import:<br />
<asp:FileUpload ID="fupExcel" runat="server" />
<br />
<br />
<asp:Button ID="btnImport" runat="server"
Text="Import" onclick="btnImport_Click" />
<br />
<br />
<a href=http://localhost:1701/SoD>Click to go to main page</a>
</form>
</body>
</html>
I am not sure how do I attach the 2 buttons to my background code, someone teach me? Best if with sample code, thanks a lot!
First, the code in your page load needs to execute only if(IsPostBack) or on button click.
Second, (At leas modern) browsers won't let you change the value of the input file field, or click it.
You might try with some flash upload thing or so, but I don't expect much.

Categories

Resources