Issue with passing hiddenfield value - c#

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

Related

How to show data from postgresql table without refreshing page (live update)?

Im making a page in razor pages asp.net c# where i want to show the values of the postgresql table, and when there is something new inserted you see the new updated table on the page without refreshing (live). I know that it probably has to do something with the notify and listen functions, but i could not find any good examples on the internet. I am a little stuck. Hope someone can show me a simple way of how to do it.
Here is the c# code:
public List<NotificationModel> ShowNotification()
{
var cs = Database.Database.Connector();
List<NotificationModel> not = new List<NotificationModel>();
using var con = new NpgsqlConnection(cs);
{
string query = "Select datumnu, bericht FROM notification ORDER BY datumnu DESC OFFSET 1";
using NpgsqlCommand cmd = new NpgsqlCommand(query, con);
{
cmd.Connection = con;
con.Open();
using (NpgsqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
}
}
con.Close();
}
}
return not;
}
And here is the html
<div class="container-fluid">
<p id ="output"></p>
<div class="col-3 bg-light">
<h5 class="font-italic text-left">Old Messages</h5>
<hr>
#foreach(var n in #Model.ShowNotification())
{
<tr>
<img class="img-fluid" src="/Images/Reservation.png"/>
<td>
#Html.DisplayFor(m => n.Datenow)
</td>
<td>
#Html.DisplayFor(m => n.Bericht)
</td>
</tr>
}
<hr>
</div>
</div>
</div>
One thing that you can do is to make ajax calls on mouse drag, first load some x number of records and show it in UI, later whenever user moves down call an ajax call on demand and send page number kind value and fetch to display on UI.
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/ControllerName/GetData';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "", //send page number here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
console.log(data); // append this to your table as applicable
}
function errorFunc() {
alert('error');
}
});
</script>
public class ControlllerName : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult Getdata(int pagenumber)
{//fetch here the data based on pagenumber
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}

How to stop page from reloading when asp button is pressed?

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

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

Calling to c# function from javascript function

I have a javascript function and c# fanction. I need to call to the c# function from the javascript function, but I don't know how...
Can someone help me?
Thank you!
The javascript function-
<script type="text/javascript" language="javascript">
function DeleteBook(idimg) {
// idimg is a string
var userConfirm = window.confirm('Are you sure?');
if (userConfirm == true) {
control.Sess(idimg);// The line which is colling to the c# function - doesn't work
window.open('Delete.aspx');
}
else
return false;
}
</script>
The c# function-
protected void Sess(string id)
{
Session["forDelete"] = id;
}
You can create a web method
[WebMethod(EnableSession = true)]
public static Application GetApplication(int id)
{
}
and in javascript you then do something like this
$.ajax(
{
type: "POST",
url: "Applications.aspx/GetApplication",
contentType: "application/json; charset=utf-8",
data: "{'id':" + id + "}",
dataType: "json",
success: methodToDoSomethingOnSuccess,
error: function (rhq, textStatus, errorThrown) {
alert ("some went awry");
}
});
you have to create an input of type submit that invokes your C# function using the HTML and make it hidden. Then create a div tag and using javascript do this:
#CSS
.Hidden {
display:none;
}
#HTML
<input type="submit" id="SubmitTag" OnClick="C# Functin" class="Hidden" runat="server" />
//if using MVC and Razor
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post)) {
<input type="submit" id="SubmitTag" class="Hidden" />
}
<div id="OnDivClick"> what you want to do in here </div>
#JS
$('#OnDivClick').click(function () {
$('#SubmitTag').trigger("click");
});
Well, there are ways to do this but I believe that you're trying to save something in the Session for the Delete.aspx page to read it. The simplest solution is just post the data in:
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', 'Delete.aspx');
form.setAttribute('target', '_blank');
form.innerHTML = '<input type="hidden" name="forDelete" value="' + idimg + '" />';
document.body.appendChild(form);
form.submit();
This dynamically creates a form and submits it with idimg which will open the page Delete.aspx in a new window.
All that's left to do is go to the C# part of Delete.aspx page and catch the incoming data:
string idimg = Request.Form["forDelete"];
// Do whatever with it
Session["forDelete"] = idimg; // If you still want to save it in Session

How to pass ms sql data to jquery float

I am developing a web application using asp.net c# and using MS SQL as database. In my application I want to plot a graph of mothly sales. For doing that I found very nice jquery plugin called flot.
But the problem is that I dont know how to pass my sql data to flot. I've a table which has two columns date (DateTime) and number of sales (int). I want the number of sales on y axis and date on x axis.
I googled alot around the web, but I didn't find much help about how to pass MS SQL data to flot.
Please any one can help me to do so.
Thanks in advance.
here is demo code
in code behind
public class chartdata
{
public string Date { get; set; }
public int Sales { get; set; }
}
[System.Web.Services.WebMethod]//public static web method in code behind
public static List<chartdata> GetData() //int StartRowindex,
{
List<chartdata> myResult= new List<chartdata>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["demo"].ConnectionString))
{
//string sqlString = "SelectbyYearTotalProductAssign";
string sqlString = "SelectbyYearTotalProductAssign1";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
chartdata obj = new chartdata();
obj.Sales = Convert.ToInt32(rdr["Sales"]);
obj.Date = rdr["Date"].ToString();
myResult.Add(obj);
}
conn.Close();
}
}
return myResult;
}
your html
<div id="chart1"></div>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
DrowChart();
});
function DrowChart() {
jQuery("#chart1").html('');
var list12 = [];
jQuery.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: "{}",
success: function (data) {
jQuery.map(data.d, function (item) {
var list = [];
list.push("'" + item.Date + "'");
list.push(item.Sales);
list12.push(list);
});
var plot1 = jQuery.jqplot('chart1', [list12],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
}
});
}
</script>
<script type="text/javascript" src="chartLib/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pointLabels.min.js"></script>
<link rel="stylesheet" type="text/css" href="chartLib/jquery.jqplot.min.css" />
You could use a jQuery Ajax call to get your flot data from server-side in JSON format. If successful then parse the JSON object and call $.plot using your placeholder div, the parsed JSON result, and any options.

Categories

Resources