Check duplicate value in the database - c#

Before I save value from TextBox into the database I need to check if that value already exists in the database.
This is the TextBox code:
<tr>
<td>
<asp:Label ID="lblProductConstruction" runat="server" Text="Product Construction:" Font-Names="Open Sans"></asp:Label></td>
<td>
<asp:TextBox ID="txtProductConstruction" runat="server" Font-Names="Merriweather" margin-Left="100px" ></asp:TextBox><br />
</td>
</tr>
<tr>
Save button:
<input type="button" class="button" id="myButton" value="Save"/>
Ajax on button click:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
WebMethod that takes the value and sends that parameter(#LvlName) to the database:
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
//string strMsg = "";
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdProc = new SqlCommand("InsertLvlName", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("#LvlName", lvl);
cmdProc.ExecuteNonQuery();
//strMsg = "Saved successfully.";
}
catch
{
}
finally
{
connection.Close();
}
return;
}
I need help to check two things:
1) To see if textbox is empty, and if this is the case then don't save the value to the database and show alert that this field needs to have some kind of a value.
2) I need some kind of a check if the same value of a field is already in the database then don't save it.
Thanks in advance !

This is the Simple Validation We can do using jquery
if (inp.val().length > 0) {
//do something
}
else
{
alert("Enter Value")
}
Full Example:-
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
if(lvl.length>0)
{
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else
{
alert("Please enter Value")
}
});
});
Second Part:-
SqlCommand checkvalue = new SqlCommand("SELECT COUNT(*) FROM [TableName] WHERE ([ColumnNameUser] = #user)" , connection);
checkvalue.Parameters.AddWithValue("#user", lvl);
int UserExist = (int)checkvalue.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
Reference Link
If you Want Sp to check then:-
Edit it based on your name and field names.
CREATE PROCEDURE InsertName
(
#username varchar(25),
#userpassword varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM MyTable WHERE username = #username)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into MyTable(username, userpassword) VALUES(#username, #userpassword)
END

First you will want to probably use jQuery to check if your textbox is empty and if it is then do not fire off the call to the webmethod. See Accessing Asp.net controls using jquery (all options) for calling asp.net controls from jQuery
if ($('#<%= myTextBox.ClientID %>').val().length == 0)
{
alert("Text Box is empty");
}
else
{
///make ajax call to webmethod...
}
Side note what do u want to happen if the user enters a space in the textbox?
Next you could either make a call to insert or update the record in the db so as to not insert any duplicates. Or I would probably want to select all data from the db and then comparing the data to see if the entry from the textbox already exists in the db.
This answer here should be helpful c# update if record exists else insert new record
Something like this should give you the result you need:
SqlCommand cmdCount = new SqlCommand("SELECT * from Table WHERE TextboxValue= #textBoxValue", myConnection);
cmdCount.Parameters.AddWithValue("#textBoxValue", _textBoxValue);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
///Run Insert statement
}

Related

code to fetch and return database string data based on dropdown box onchange event through .net controller class to form page using ajax

C#,ASP.NET MVC,Ajax:-I have a form page where there is a drop down list showing customers name from database table customers.Based on the customer selection by passing customer id to database table I want to fetch his email id and contact number and display it in form read only text fields.My problem is controller code is not working.In other words i am not able to check whether id is reaching my controller function to fetch data and the query is executing or not.I am getting error function data on form page
My jquery code is as below
CustomerList1 is the id for drop down box
var cusKey to hold customer id
GetCustmrDetails is my controller function to fetch data based on id
$("#CustomerList1").change(function (event) {
var cusKey = $("#CustomerList1").val();
alert("customerKey:" + cusKey);
$.ajax({
type: 'GET',
url: "/CustomerController/GetCustmrDetails/",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ "id": cusKey }),
success: function (data) {
alert("available");
$("#EMailAddress").val(data.EMailAddress);
$('#Phone').val(data.Phone);
},
error: function () {
alert("error");
}
});
});
My controller code is as below
[HttpGet]
public ActionResult GetCustmrDetails(int id)
{
List<CustomerModel> customer = new List<CustomerModel>();
string query = string.Format("Select EMailAddress,Phone From
OC_Customer where CustomerKey="+id);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
customer.Add(new CustomerModel{
EMailAddress = reader["EMailAddress"].ToString(),
Phone = reader["Phone"].ToString()
});
}
}
return Json(customer, JsonRequestBehavior.AllowGet);
}
}
I want email id and contact number to display on form page(cshtml)
please use this one
$("#CustomerList1").change(function (event) {
var cusKey = $(this).val();
alert("customerKey:" + cusKey);
$.ajax({
type: 'GET',
url: "/Customer/GetCustmrDetails?id="+cusKey,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (data) {
alert("available");
$("#EMailAddress").val(data[0].EMailAddress);
$('#Phone').val(data[0].Phone);
},
error: function () {
alert("error");
}
});
});

Ajax JSON call to back-end function always triggers error response, even though function works correctly

I have the following JSON Ajax call:
$.ajax({
url: '#Url.Action("AddOrUpdateTimeEntry", "TimeEntries")',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: payload,
success: function (data) {
var id = data.TimeEntryID;
$(this).parent().parent().parent().attr('id', id);
}
error: alert("Error Saving Data - changes not saved to database")
});
which calls this function:
public ActionResult AddOrUpdateTimeEntry(TimeEntryData ted)
{
int rowId = Convert.ToInt16(ted.RowId.Split('_')[1]);
// If RowId = 0, it's a new row so create, otherwise update
bool IsNewRow = rowId == 0;
int hours = ted.Hours;
TimeEntry te;
if (IsNewRow)
{
te = new TimeEntry();
te.ClientID = ted.ClientID;
te.TaskTypeID = ted.TaskTypeID;
}
else
{
te = (from t in db.TimeEntries
where t.TimeEntryID == rowId
select t).FirstOrDefault();
}
switch (ted.DayOfWeek)
{
case "Mon":
te.MonHours = hours;
break;
...
}
if (IsNewRow) // New row, so create a new entry in database
{
db.TimeEntries.Add(te);
}
db.SaveChanges();
var id = te.TimeEntryID;
return Json(new { TimeEntryID = id });
}
The function works, in that the database is updated correctly, but the error: function:
error: alert("Error Saving Data - changes not saved to database");
is always fired. (I assume that the row id is not updated either as per the success: function.)
Assign a function to error:
error: function() {
alert("Error Saving Data - changes not saved to database");
}
Try returning an int rather than Json.
I find that a lot of the time this can sometimes happen when you mis-declare the datatype or return incorrect data.

Ajax Call not working with asp.net

Ajax Call not working. When I click on btnsubmit, it first shows alert hi and then "Record Save to Database" but data not saving to database. The stored procedure name is "Ajax".
How to solve the error? Thanks in advance..
Procedure is:
create procedure Ajax
#EmpID nvarchar(50),
#EmpName nvarchar(50),
#EmpAddress nvarchar(50)
as
begin
insert into NewEmp (EmpID, EmpName, EmpAddress)
values (#EmpID, #EmpName, #EmpAddress)
end
HTMl Page:
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
var EmpID = $('#TxtID').val();
var EmpName = $('#TxtName').val();
var EmpAddress = $('#TxtAdd').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default11.aspx/InserData",
data: "{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}",
dataType: "json",
success: function (response) {
alert("Hi");
$("#TxtID").val(''); $("#TxtName").val(''); $("#TxtAdd").val('');
alert("Record Save to Databse");
},
error: function () {
alert("Error");
}
});
});
});
</script>
<div>
<asp:TextBox ID="TxtID" runat="server" ></asp:TextBox>
<br />
EmpName:-<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
<br />
Addresss:-<asp:TextBox ID="TxtAdd" runat="server"></asp:TextBox>
<br />
<input type="button" id="btnsubmit" value="Submit" />
</div>
C# 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;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
public partial class Default11 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static bool InserData(string EmpID, string EmpName, string EmpAddress)
{
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["AjaxInsert"].ConnectionString);
try {
SqlCommand cmd = new SqlCommand("Ajax",scon);
scon.Open();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText = "Ajax";
cmd.Parameters.AddWithValue("#EmpID", EmpID);
cmd.Parameters.AddWithValue("#EmpName", EmpName);
cmd.Parameters.AddWithValue("#EmpAddress", EmpAddress);
cmd.Connection = scon;
cmd.ExecuteNonQuery();
scon.Close();
// return "success";
}
catch(Exception ex)
{
// return"error";
}
return true;
}
}
You are use asp control for get input values from user. so make changes in jQuery code as given below. because i was also face same problems. So i hope it would help to you.
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
var EmpID = $('#<%=TxtID.ClientID%>').val();
var EmpName = $('#<%=TxtName.ClientID%>').val();
var EmpAddress = $('#<%=TxtAdd.ClientID%>').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default11.aspx/InserData",
data: "{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}",
dataType: "json",
success: function (response) {
alert("Hi");
$('#<%=TxtID.ClientID%>').val('');
$('#<%=TxtName.ClientID%>').val('');
$('#<%=TxtAdd.ClientID%>').val('');
alert("Record Save to Database");
},
error: function () {
alert("Error");
}
});
});
});
</script>
Have you checked via breakpoints the string the following command.
"{'EmpID':'" +EmpID + "','EmpName':'" + EmpName + "','EmpAddress':'" + EmpAddress + "'}"
returns to server?
Why not data: { EmpID: EmpID , EmpName: EmpName , EmpAddress: EmpAddress } ?
you cant use asp controls in java scritpt .becase asp controls can be accessable at out side i.e server side only .insted of server contols use html controls like below
EmpID:-
EmpName:-
Addresss:-

Tag System in Asp.net

I want to create a tagging system for my website which allows user to enter the required skills,separated by comma, using ASP.net and C#.
In detail:
A textbox will receive tags, separated by comma.
Suggestions will be provided while typing, based on AVAILABLE tags in my database.
Suggested tags will be displayed, below the textbox.
If a new tag is encountered, it is inserted into database.
The tags (separated by comma), given by the user could be further manipulated according to my needs (a way of doing that).
I want to make a separate entry for each and every tag into the database.
I tried using Tag-it by Levy Carneiro Jr.. it is working perfect for local source.
But when I tried attaching it with my database using this. It just doesn't work.
My code:-
<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: "tag.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('singleFieldTags2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
<script>
$(function () {
//Local sample- //var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
$('#singleFieldTags2').tagit({
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox name="tags" id="singleFieldTags2" value="Apple, Orange" class="autosuggest" runat="server"></asp:TextBox>
</form>
Backend C# code-
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=ZESTER-PC;Initial Catalog=mystp;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select tag_name from tags where tag_name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["tag_name"].ToString());
}
return result;
}
}
}
Here tags is my tag table containing tag_id and tag_name.
I have created the Tagging System using ASP.net
Check it out.. nd do rate it..
Tagging System using ASP.net by Sumanyu Soniwal

auto complete on asp.net control

hey I want to use autocomplete jquery in asp.net on a control which is used on a default1.aspx page. My control is searchinput.ascx which is in Registration folder. My ploblem is I have written web method (getmylist) on code file of searchinput control. but that method is never called. can anyone help me
Jquery website
You can find wat you need there for a start.
Also, show your ajax call so that I can try helping on y it is not working.
Your approach of writting a web method and making a ajax call from the jquery auto complete should work out fine otherwise.
Its hard to help you without the code but some common causes could be:
You are not using ClientID value correctly - asp.net controls dont have the same id in the actual mark-up as they do in the designer
your web method has an error in it - you should press f12 to open your web developers toolbar and go to NET tab (in firefox at least) to see if a 500 error code or similar is being returned
Create a web method like the following:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientFirstName(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
string connectionstring = CCMMUtility.GetCacheForWholeApplication();
conn.ConnectionString = connectionstring;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select distinct top(10) PatientFirstname from tblMessage where " +
"PatientFirstname like '%'+ #SearchText + '%' order by PatientFirstname";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}", sdr["PatientFirstname"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
here is the html code :
$(document).ready(function () {
$('[ID$=txtPatientFirstname]').live('keyup.autocomplete', function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientFirstName") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
},
minLength: 1
});
});
});
This is the working example ......hope this will solve your problem..

Categories

Resources