I have created form with many fields that on page load loads information about a specific user. When the user click on the button update the page seems to be reloading and then sends the sames informations to the server.
I have looked at similaire answers on stackoverflow but none seem to work for me.
Here is my front end.
<asp:TextBox ID="BirthDate" type="text" runat="server" class="form-control"
placeholder="fecha nacimiento" aria-describedby="inputGroupPrepend"
required="required"></asp:TextBox>
<asp:Button class="btn btn-primary" ID="update" runat="server" Text="actualizar" AutoPostback="false" OnClick="update_Click"/>
and here is my back end.
//This is where the textboxes are populated
protected void Page_Load(object sender, EventArgs e)
{
string employeID = gestiondeempleados.empleadoID;
string queryStr = "SELECT empleado_id,nombreusuario,nombre Where empleado_id =" + employeID;
using (conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
using (cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn))
{
conn.Open();
using (reader = cmd.ExecuteReader())
{
if (reader.Read())
{
firstname.Text = reader.GetString(reader.GetOrdinal("nombre"));
}
}
}
}
//This is where the change textbox should be send to the database
protected void update_Click(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string UpdateStatement1;
UpdateStatement1 = "update erp_empleados set " +
"nombre = '" + firstname.Text "' where empleado_id = " +
gestiondeempleados.empleadoID;
debugmsg.Text = UpdateStatement1;
//MySql connection code....
}
}
I want the changed text field to be send and not same text field I have loaded initial.
I suggest to use Ajax request instead of asp.net web forms events, this is the standard and modern approach to submit data without postback in any web applications framework.
You need to create a web method and call it , you can search more "asp.net web method ajax jquery calling"
$('#btnSave').click(function (e) {
e.preventDefault(); //
var element = this;
$.ajax({
url: "YOUR_WEB_METHOD_URL",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Or you can use update panel (Very easy approach and you will use same asp.net events but I'm not recommended this approach because its inject a lot of not clear scripts to your page and its not the best practice from security side and maybe partially not working with some modern versions of browsers).
To use update panel please take look on below link
https://www.c-sharpcorner.com/UploadFile/f50501/use-updatepanel-control-in-Asp-Net/
I figured it out.All I hate to do was adding !IsPostBack were the variable where initialized. I am not sure why doe could anyone clarify the reason.
//This is where the textboxes are populated
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string employeID = gestiondeempleados.empleadoID;
string queryStr = "SELECT empleado_id,nombreusuario,nombre Where empleado_id =" + employeID;
using (conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
using (cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn))
{
conn.Open();
using (reader = cmd.ExecuteReader())
{
if (reader.Read())
{
firstname.Text = reader.GetString(reader.GetOrdinal("nombre"));
}
}
}
}
}
Related
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
}
Please help.
I have 3 dropdowns :
1. Country
2. Port
3. Company Name
Once 1st dropdown (countries) is selected, 2nd dropdown should be populated with a list of specific ports, then based on 1st and 2nd dropdown, the 3rd dropdown will be populated also.
this is a one time key-in. Meaning once selection is done, the user will save it in db and the value should remain in the dropdown unless the user change.
Right now, i'm using OnSelectedIndexChanged which is very slow because of the postback.
let me know if there's any other way of doing.
Thanks,
Jack
there could have several ways to achieve this. One of the ways is using WebService [WebMethod]. Ajax and JSON.
//You databinding method must be public and add [WebMethod] attribute
[WebMethod]
public static List<ListItem> GetCustomers()
{
string query = "SELECT CustId, CustName FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> custListItem = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
custListItem.Add(new ListItem
{
Value = Convert.ToString(sdr["CustId"]),
Text = Convert.ToString(sdr["CustName"])
});
}
}
con.Close();
return custListItem;
}
}
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "CustomerList.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlCustomers = $("[id*=ddlCustomers]");
ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
</script>
You basically have 2 options, preload your values into a js structure (counties, ports and companies), or use a ajax/xmlhttprequest call to load just the relevant information (just the ports for a specific country). If preloading the values, you can either mix it in with your html in the body of a script tag, or have it be a seperate file that is loaded via a src attribute.
Which is best to use will vary based upon your user base and data size, and how frequently the data changes.
I'm have a comment system on a project where you can view different pages and they have their own comments. I'm trying to use signalR with SqlDependency to automatically pull new comments on the page.
My problem is that if multiple people have a connection open with SqlDependency the number of "onchange" events called from the sqlnotification start getting multiplied. Instead of the onchange even getting called once it will be called multiple times for each user. (Even if they are not viewing the same comments page)
I've pretty much exhausted all searching here with the most common response being that I need to unsubscribe the event when it's called like this:
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
if (e.Info.ToString().ToLower().Trim() == "insert")
{
MyHub.Show();
}
}
This didn't seem to change anything for me so I'm lost on what the best way to prevent this would be.
GetData method:
[WebMethod]
public IEnumerable<DUpdates> GetData(string dnum, string date)
{
if (Common.IsValidInt32(dnum)) //just a function that check for valid int
{
using (var connection =
new SqlConnection(ConfigurationManager.ConnectionStrings["SConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Comment] FROM dbo.DUpdates WHERE (DID = " + dnum + ") AND (Deleted = 0) AND CreateDate > #Date ORDER BY CreateDate DESC", connection))
{
command.Parameters.Add("#Date", SqlDbType.DateTime);
command.Parameters["#Date"].Value = date;
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new DUpdates()
{
comment = x.GetString(0)
}).ToList();
}
}
}
}
JS stuff:
$(function() {
var job = $.connection.myHub;
job.client.displayStatus = function () {
getData();
};
$.connection.hub.start();
getData();
});
function getData() {
var params = (new URL(document.location)).searchParams;
var id = params.get("id");
var dt = $("#accessdate").val();
$.ajax({
url: 'dupdatesservice.asmx/GetData',
data: JSON.stringify({dnum: id, date: dt}),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (data) {
if (data.d.length > 0) {
$("#testdiv").prepend(data.d[0].comment);
}
}
});
}
Can provide other code if needed.
The issue here is that I was creating a new SqlDependency for each user that was on a page (or same user with multiple windows). So if 2 windows were open for a page, then it would check for notifications twice and send the response twice if there was something new. Because of the ajax request, now all of those SqlDependencies were doubled so I'd get 4 responses the next time, then 8 and so on.
What I decided to do instead was to essentially change my pages to private chats using signalr and just ditched the SqlDependency stuff. So now if a user goes to one page, they are connected with anyone else on the page and anytime someone submits a "comment" it also gets sent to other people viewing the page.
I am trying to pass HiddenField value to WebMethod GetAutoCompleteData to enable auto complete in text box based on selected search field.
I have tried pass HiddenField values using code-behind, but it didn't work.
There is no issues with javascript codes.
Note: I have tried to use HiddenField value in another method, and it worked, so I am sure that HiddenField is taking values using JavaScript code.
Code-behind:
public static string hdnvalue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
hdnvalue = hdnSearchParam.Value;
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value)
{
string hiddenfiedlvalue = hdnvalue;
List<string> result = new List<string>();
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("select #hiddenfiedlvalue from Users where #hiddenfiedlvalue LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", value);
cmd.Parameters.AddWithValue("#hiddenfiedlvalue", hiddenfiedlvalue);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}", hiddenfiedlvalue));
}
return result;
}
}
}
Code used to pass selected values from drop-down menu to HiddenField:
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var param = $(this).attr("href").replace("#", "");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
$('[id$=hdnSearchParam]').val(param);
});
});
</script>
Auto complete code:
<script type="text/javascript">
$(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'value':'" + $('#txtSearch').val() + "'}",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
}
else {
response([{ label: 'No Records Found', val: -1 }]);
}
},
error: function (result) {
alert("Error");
}
});
},
});
}
</script>
ASPX:
<asp:HiddenField ID="hdnSearchParam" runat="server" />
<div class="col-xs-8">
<div class="input-group">
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">Filter by</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>User ID</li>
<li>User Type</li>
<li>User Name</li>
<li>First Name</li>
<li>Last Name</li>
<li>Email</li>
</ul>
</div>
<input type="hidden" name="search_param" value="all" id="search_param">
<asp:TextBox ID="txtSearch" CssClass="autosuggest form-control" runat="server"></asp:TextBox>
<span class="input-group-btn"></span>
</div>
</div>
Your page has several issues.
First, why are you using a hidden field for this? Why don't you just pass the dropdown value as a second parameter in the Ajax request?
Second, in your code behind you are reading the hidden value only on page load, and that value is never updated with each Ajax request (Page_Load is not executed again). You made that static trick with hdnvalue just to make it compile, but it won't work. Also, making it static makes it be shared among all web clients using that page!
Third, why are you storing the dropdown value in its href as well? You could use a span or even simple text instead.
Fourth, you are using the server controls markup ID instead of the ClientID, which may be different depending on the .NET framework you are using. Better play safe and use ClientID always.
Fifth, if with jQuery you select by ID, just use the ID, there's no need to use any other class selectors. Of course, you should never have repeated IDs!
Sixth, you can't use parameterized variables as column names. You must use a dynamic query. More info about that here. Also the reader wasn't working properly (only adding the hidden field) and it's better to enclose the ExecuteReader in a using block.
Summarizing, use this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+#SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var concept = $(this).text();
$('#search_concept').text(concept);
});
});
</script>
Important: if you are afraid of SQL Injection, you may want to do some validation with filterBy first.
In your Javascript, fix this line only:
data: "{'value':'" + $('#<%= txtSearch.ClientID %>').val() + "','filterBy':'" + $('#search_concept').text() + "'}",
Finally, just get rid of both hidden fields (user control and html control).
try to change data parameter to this:
data: "{'value':'" + $('#hdnSearchParam').val() + "'}",
Try removing the dollar sign from this line of code.
$('[id$=hdnSearchParam]').val(param);
It should be smthing like this:
$('[ID="hdnSearchParam"]').val(param);
I do something to pass Facebook ressponse by post the value to currentpage
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
$.post('http://localhost:50790/TestPage.aspx',
{ fbid: response.id, firstname: response.first_name, lastname: response.last_name, email: response.email, bday: response.birthday },
function (result) {
});
console.log('Good to see you, ' + response.name + response.id + response.email + response.gender + response.birthday + '.');
});
}
and I do some checkin on my code behind :
protected void Page_Load(object sender, EventArgs e)
{
var fbid = Request.Form["fbid"];
var fname = Request.Form["firstname"];
var lname = Request.Form["lastname"];
var email = Request.Form["email"];
var bday = Request.Form["bday"];
if (!Page.IsPostBack)
{
if (fbid != null)
{
CheckFBLogin(fbid.ToString());
}
}
}
my testing is on CheckFBLogin if the result okay, It'll make the user login to website, else it should redirect to others page / registration page.
public void CheckFBLogin(string Fbid)
{
CustomerSelfCareSoapClient service = new CustomerSelfCareSoapClient();
service.ClientCredentials.UserName.UserName = _Username;
service.ClientCredentials.UserName.Password = _Password;
GResult result = service.CheckFBLogin(Fbid.ToString(), "");
if (result != null)
{
if (result.Code == 100)
{
//login
}
else
{
Response.Redirect("~/callback.aspx", true);
}
}
}
I dont know what happen, I usually do something like this to check login but pure asp and c#. any I idea why the page wont redirect ?
I'm able to duplicate this behavior with Mono. On my system, the problem is that the jquery $post() method actually enables the Page.IsPostBack property in code behind so that all logic in the if (!Page.IsPostBack) {} condition fails to run.
My advice would be use ASP.NET's [WebMethod] attribute alongside jquery. Dave Ward has documented this well. If you're doing a lot of asynchronous client side JSON calls, you might consider ASP.NET's MVC implementation if the scope of your project allows it.