Insert data into database using ajax - javascript

I am using ajax to insert data in database
My default .aspx file is as below
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%= btn_Insert.ClientID %>").click(function () {
//var name = $('#<%=txt_name.ClientID%>').val();
//var email=$('#<%=txt_email.ClientID%>').val()
var email = document.getElementById('txt_email').value;
var name = document.getElementById('txt_name').value;
//alert("{'Name':'" + name + "', 'Email':'" + email + "'}");
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: "Name=" + name + "&Email=" + email,
//data: $('#form1')
async: true,
success: function (response, data)
{
$('#txt_name').val('');
$('#txt_email').val('');
alert("Record Has been Saved in Database");
alert(response.data.name);
},
error: function () {
console.log('there is some error');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
Name : <asp:TextBox ID="txt_name" runat="server" ClientIDMode="Static"></asp:TextBox>
</p>
<p>
E-mail : <asp:TextBox ID="txt_email" runat="server" ClientIDMode="Static"></asp:TextBox>
</p>
<p>
<asp:Button ID="btn_Insert" runat="server" Text="INSERT" OnClick="btn_Insert_Click"/>
</p>
</div>
</form>
</body>
</html>
and my .cs file is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string Name = Request["Name"];
string Email = Request["Email"];
InsertMethod(Name, Email);
}
SqlCommand cmd;
public Boolean InsertMethod(string Name, string Email)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
cmd = new SqlCommand("insert into dbo.Demo_AJAX (Name,Email)values (#name,#email)", conn);
cmd.CommandType =CommandType.Text;
cmd.Parameters.AddWithValue("#name",Name);
cmd.Parameters.AddWithValue("#email", Email);
try
{
conn.Open();
//cmd.ExecuteNonQuery();
int affected = cmd.ExecuteNonQuery();
if (affected == 1)
{
//Response.Write("Bhargav");
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
//Response.Write(ex.Message);
return false;
}
finally
{
conn.Close();
}
}
protected void btn_Insert_Click(object sender, EventArgs e)
{
}
}
When I run then it insert one blank data in database.
I don't know how to solve it.
Please any one help me.

Use webmethod then its working.
add namespace
using System.Web.Services;
Change Your Method Like
[WebMethod]
public static Boolean InsertMethod(string Name, string Email)
and remove
<asp:Button ID="btn_Insert" runat="server" Text="INSERT" />
and remove click event from .CS page
then its working.

Related

click()/code behind is no longer execute after set InputFile

I write a page for upload a file to a server.
Before the file is uploading, there should be a question for override the file(if it on the server already)
The check(code behind/Event IndexChange) is set a variable in the client script.
If the user press the "Upload" button a script(confirm_user) check the variable and show a confirm dialog (Override ? Yes/No) and then call a C# function.
It is a ASPX Control running in a IFrame with Masterpage.
My problem:
If I test it without set an input file, it works(break point in code).
But if I select a file for upload the function is not called(press the normal Upload button works fine).
ASCX File
<%# Control Language="C#" AutoEventWireup="True" Inherits="Test_Web.UploadProgress" Codebehind="UploadProgress.ascx.cs"%>
<link rel="stylesheet" href="css/alertify.css" />
<link rel="stylesheet" href="css/themes/default.css" />
<script src="alertify.js"></script>
<script type='text/javascript'>
//hold Check state
var override = -1;
//Script is working, except Click()
function confirm_user() {
if (override == 1) {
if (confirm('Overrride?')) { document.getElementById('<%=btn_upload_nocheck.ClientID%>').click();
return true;
}
else
return false;
}
else if (override == 0) { document.getElementById('<%=btn_upload_nocheck.ClientID%>').click();
return true;
}
return false;
function setoverride(ov) {
override = ov;
alertify.alert('Info','Test: '+ ov);
}
//}
</script>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="up_message">
<ContentTemplate>
<asp:DropDownList runat="server" ID="dd_sendungstitle" OnSelectedIndexChanged="dd_sendungstitle_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>t1</asp:ListItem>
<asp:ListItem>t2</asp:ListItem>
<asp:ListItem>t3</asp:ListItem>
<asp:ListItem>t4</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" ID="lbl_progress"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<br/>
<input type="file" id="upUserCtrl" runat="server"/>
<br/>
<asp:Button ID="btn_upload_nocheck" runat="server" Text="Upload" Width="101px" align="center" OnClick="btn_upload_nocheck_Click"/>
<asp:Button runat="server" ID="btnTest" OnClientClick="return confirm_user();" Text="Upload Script"/>
Code behind File
public partial class UploadProgress: System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
...
private void ShowMessage(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("<body><script type='text/javascript'>alert('" + msg + "');</script></body>");
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
}
protected void btn_upload_nocheck_Click(object sender, EventArgs e)
{
Upload(false);
}
private void Upload(bool docheck)
{
//Upload File
int t = _override;
...
ShowMessage("File(" + filename + ") uploaded");
}
protected void dd_sendungstitle_SelectedIndexChanged(object sender, EventArgs e)
{
// Do Checking STuff
if (dd_sendungstitle.SelectedIndex == 0 || dd_sendungstitle.SelectedIndex == 3)
{
_override = 0;
}
else
{
_override = 1;
}
//Set Client Script
ScriptManager.RegisterStartupScript(Page,typeof(string), "javascript", "setoverride(" + _override + ")", true);
}
}

AJAX call method on another page

I have a list, and when I click a row on that list, I have AJAX syntax that passes an ID to a method in the code behind, and returns the data to some html elements. This works fine, but right now it returns the data to html elements that are on the same page. What if I wanted to have it navigate to another page to display the data? So here is my current code:
My aspx page
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="listPage.aspx.cs" Inherits="listPage" %>
<!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>Call C# method/function using JQuery Ajax</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#matchupTable tr').click(function () {
var gameID = $(this).attr('id');
//var gameID = '19';
$.ajax({
url: 'listPage.aspx/GetMatchupByID',
method: 'post',
contentType: "application/json",
data: '{gameID:' + gameID + '}',
dataType: "json",
success: function (data) {
$('#awayCity').text(data.d.AwayCity);
$('#awayTeam').text(data.d.AwayTeam);
$('#home').text(data.d.Away);
$('#homeCity').text(data.d.HomeCity);
$('#homeTeam').text(data.d.HomeTeam);
$('#home').text(data.d.Home);
},
error: function (err) {
alert(err);
}
});
});
});
</script>
</head>
<body>
<%-- LIST AREA --%>
<form id="form1" runat="server">
<div>
<table id="matchupTable">
<tr style="cursor: pointer;" id="25"><td>Click me, I won't hurt you</td></tr>
</table>
</div>
</form>
<%-- RESULTS AREA --%>
<div id="awayTeamDiv">
<div id="awayTeamTitle">
<h5 id="awayCity"></h5>
<h3 id="awayTeam"></h3>
<p id="away"></p>
</div>
</div>
<div id="homeTeamDiv">
<div id="homeTeamTitle">
<h5 id="homeCity"></h5>
<h3 id="homeTeam"></h3>
<p id="home"></p>
</div>
</div>
</body>
</html>
My code behind
using System;
using System.Web.Services;
using GamblersDenNet;
using System.Data;
using System.Data.SqlClient;
public partial class listPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Matchup GetMatchupByID(int gameID)
{
Matchup matchup = new Matchup();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#GameID",
Value = gameID
});
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
matchup.GameID = reader["GameID"].ToString();
matchup.Date = reader["Date"].ToString();
matchup.HomeCity = reader["HomeCity"].ToString();
matchup.HomeTeam = reader["HomeTeam"].ToString();
matchup.Home = reader["Home"].ToString();
matchup.AwayCity = reader["AwayCity"].ToString();
matchup.AwayTeam = reader["AwayTeam"].ToString();
matchup.Away = reader["Away"].ToString();
}
return matchup;
}
}
So, if I wanted to instead have a detailsPage.aspx, and when I clicked the tr element, it redirected to this detailsPage.aspx and executed the code, what would that look like? I know I'd have to move my div elements in the RESULTS AREA of my listPage.aspx to the other page, and maybe set that stored procedure to execute on page load, but how would I pass it the parameter from the row I clicked? What would that look like?
In the interest of brevity I removed some extraneous code, so I'm sorry if there may be some syntax errors in my example.
Thanks all!
Try to just make a normal http post request rather than an ajax and have your endpoint GetMatchupByID return a view with your object Matchup as the view model.
See this link for returning a view and passing a view model to it:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part3#passing-a-viewmodel
My solution to this problem was to use pass the value using a query string:
$('#matchupTable tr').click(function () {
var gameID = '/detailsPage.aspx?gameID=' + $(this).attr('id');
window.location.href = gameID;
});
and then on the Page_Load of detailsPage, I moved the code of GetMatchupByID(), and passed it the parameter by using:
string GameID = Request.QueryString["gameID"];
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TrinoviContext"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("usp_GetMatchupDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GameID", GameID);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// populate properties I need for display on page
}
con.Close();

YesNo Confirmation ASP.NET

I am trying to get a Yes No Prompt to show client side after an if statement in code, and depending on what the user clicks to execute code.
So far I have the following:
if (barcodes[t].ToString() == txtBarcode.Text)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>confirm('Item Already in Order, Continue?');</script>");
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Ok")
{
itemAdd();
DBConnect.DisplayMessage(this, "Added to order");
}
else
{
DBConnect.DisplayMessage(this, "Not added");
return;
}
}
I envoke a script in the third line of the above code, which shows correctly.
However regardless of what the user chooses, it will always return negative.
Thanks in advance :)
Here's a nice and simple solution from Mudassar Ahmed Khan's website that fits your needs:
PageClientScript.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PageClientScript.aspx.cs" Inherits="PageClientScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDisplayMessage" runat="server" Text="Click the button to display a confirm dialog."></asp:Label>
<br /><br />
<asp:Button ID="btnConfirm" runat="server" OnClick="OnConfirm" Text="Raise Confirm" OnClientClick="Confirm()"/>
</div>
</form>
</body>
</html>
PageClientScript.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 PageClientScript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.lblDisplayMessage.Text = "Added to order!";
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.lblDisplayMessage.Text = "Not added to order!";
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
}
Results:

telerik radgrid get_masterTableView() not taken on binding json data to radgrid

I am binding an array of list from json to telerik RadGrid from client side. The code for binding the data object to radgrid is shown below:
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function SetInTelerikGrid(data) {
var tableView = $find('<%=rgRetrievalList.ClientID %>').get_masterTableView();
tableView.set_dataSource(data);
tableView.dataBind();
}
</script>
</telerik:RadCodeBlock>
The radgrid definition is:
<telerik:RadGrid ID="rgRetrievalList" runat="server" >
<MasterTableView TableLayout="Auto">
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID" >
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Here, as the code reached var tableView = $find('<%=rgRetrievalList.ClientID %>').get_masterTableView(); an error is thrown: Typeerror: cannot read property 'get_masterTableView()' of null. I do not know why it is note able to take property get_masterTableView() of radgrid. Can anyone help me?? Thanks in advance..
As you are trying to bind Radgrid with JSON data that's why you got this error.
To resolved this issue either you have to bind your radgrid using client side binding method or add dummy data for json data binding.
Add dummy data for json data binding:
ASPX
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<script src="Script/jquery-1.10.2.min.js"></script>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
var GridData;
function OnbuttonClient() {
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '',
dataType: 'JSON',
url: 'Forum.aspx/BindGrid',
success: function (result) {
GridData = result.d;
if (GridData.length > 0) {
var divGridContainer = document.getElementById('divGridContainer');
divGridContainer.style.display = "";
var tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
tableView.set_dataSource(GridData);
tableView.dataBind();
}
else {
var divGridContainer = document.getElementById('divGridContainer');
divGridContainer.style.display = "none";
}
},
error: function () {
alert('Error on binding the data');
}
});
return false;
}
</script>
</telerik:RadCodeBlock>
</head>
<body>
<form id="form1" runat="server">
<div>
<telerik:RadScriptManager ID="RadScriptManager1" EnablePageMethods="true" runat="server">
</telerik:RadScriptManager>
<asp:Button ID="Button1" Text="Bind Grid" runat="server" OnClientClick="return OnbuttonClient();" />
<div id="divGridContainer" style="display: none;">
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false">
<MasterTableView HierarchyLoadMode="Client" DataKeyNames="ID,ParentID" ClientDataKeyNames="ID,ParentID">
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</div>
</div>
</form>
</body>
</html>
ASPX.CS
protected void Page_Init(object source, System.EventArgs e)
{
}
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dynamic data = new[] {
new { ID = "1", Name ="Name11",ParentID = "0"}
};
RadGrid1.MasterTableView.DataSource = data;
RadGrid1.DataBind();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Employee> BindGrid()
{
List<Employee> list = new List<Employee>(); ;
Employee obj = new Employee();
obj.ID = "1";
obj.Name = "Name1";
list.Add(obj);
obj = new Employee();
obj.ID = "2";
obj.Name = "Name2";
list.Add(obj);
return list;
}
[Serializable]
public class Employee
{
public string ID { get; set; }
public string Name { get; set; }
}
Please check this link for more detail.

Converting Serverside C# to ASP.NET Web API

After posting on how to get server side information to JS (on client side) link here, I was advised to create my server side logic into a Web Api in order to expose data via HTTP through a JQuery AJAX call. After looking through a lot of documentation, and even a tutorial series online hosted by Microsoft, I found little to no good instruction. Previously, I was calling my serverside methods through inline C# calls in my js script, but learned that because C# is precompiled, it simply just "fills in" the values returned by the C# functions.
Just for a reference as to how I am improperly calling my C# methods.
This is my front end: 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";
}
}
How can I convert my C# into Web api's? I would very much appreciate it if any answers could link me to good documentation or tutorials.
Moving this into Web API would require creating a new Web API project, setting up your appropriate controllers, and moving Form Control to parameters to pass into the Controller methods. Please visit this tutorial for more information on getting started with ASP.NET Web MVC: Getting Started With ASP-NET Web API
Please Note: Executing dynamic SQL the way you are doing in the above code leaves your application open to SQL Injection attacks! Please consider using parameterized SQL instead.

Categories

Resources