c# how to get asp.net textbox value inside static web method? - javascript

I want to call c# methods from JavaScript timer like below.
<script type="text/javascript">
window.setInterval(DeleteKartItems, 10000);
function DeleteKartItems() {
PageMethods.DeleteItem();
alert("test");
}
</script>
c# methods
public static void DeleteItem()
{
string query = "[Get_Messages]";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#roomId", 5);
GetData(cmd);
}
private static void GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["LinqChatConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Messages");
}
}
}
}
So how to get Label/TextBox value inside above methods?
I tried like below but its getting null value..
Page page = HttpContext.Current.Handler as Page;
Label lblRoomId = (Label)page.FindControl("lblRoomId");
string lbRoomId = lblRoomId.Text;
ANY SUGGESTION ?

Pass the label/textbox value in parameter.
PageMethods.DeleteItem(txtValue);
public static void DeleteItem(string txtValue)
{
// perform operation
}

Related

How to create a webapi that returns sqldatareader data in c#?

I am using asp.net core. I need to display the data in the select dropdown in react from web api. WebApi GET method that returns SQL DataReader. Reader returns one row with prodid, prodname, and proddescr columns. Please help what the best way to write a get web api that uses SQL DataReader for filling the select dropdown in react.
[HttpGet("{ProductID}")]
public JsonResult GetProductInfo(int ProductID)
{
var response = GetProductInfo(ProductID);
return new JsonResult(response);
}
public string GetProductInfo(int Product_ID)
{
SqlConnection objConnect = new SqlConnection(_connectionString);
SqlCommand objCommand = new SqlCommand("usp_GetProdInfo", objConnect);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter("#Product_ID", SqlDbType.Int, 4));
objCommand.Parameters["#Product_ID"].Value = intProduct_ID;
string json = string.Empty;
List<object> objects = new List<object>();
objConnect.Open();
SqlDataReader reader = objCommand.ExecuteReader();
while (reader.Read())
{
IDictionary<string, object> record = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
record.Add(reader.GetName(i), reader[i]);
}
objects.Add(record);
}
json =JsonConvert.SerializeObject(objects);
reader.Close();
objConnect.Close();
return json;
}
you don't need to serialize data, Net can do it for you. And it is a very bad programming style to use objects instead of real classes. So return List instead of List
public ActionResult<List<Product>> GetProductInfo(int ProductID)
{
var response = GetProductInfoList(ProductID);
if (response != null) return Ok(result)
else retun BadRequest();
}
public List<Product> GetProductInfoList(int Product_ID)
{
List<Product> products = new List<Product>();
...fix the code to get typed List<Product> from reader
return products;
}

Webmethod jquery ajax call not returning any results

Hi I am building a web media gallery for which,
I've a simple webmethod to fetch tags from database.
public class Tags
{
public string tag_ID { get; set; }
public string tag { get; set; }
public string total_count { get; set; }
}
[WebMethod]
public static List<Tags> GetTags()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["taggerConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetTagCount";
cmd.Connection = conn;
List<Tags> tag = new List<Tags>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
tag.Add(new Tags
{
tag_ID = sdr["tag_ID"].ToString(),
tag = sdr["tag"].ToString(),
total_count = sdr["total_count"].ToString()
});
}
}
conn.Close();
return tag;
}
}
}
and a javascript which I call on button click to display the result in a div.
But I am not getting any result in the call. No errors are also being displayed.
$(document).ready(function () { $('#getTags').click(myFunction); });
function myFunction() {
$.ajax({
type: "POST",
url: "/App/WebForm1.aspx/GetTags",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var Tags = response.d;
$(Tags).each(function () {
var tag = this.tag;
$("#results").append(" <b>" + tag + "</b>. ");
})
};
}
You are missing a line after cmd.CommandText = "GetTagCount"; it is cmd.CommandType = CommandType.StoredProcedure;
Setting this in Web.Config:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
You webservice code will be:
public class Tags
{
public string tag_ID { get; set; }
public string tag { get; set; }
public string total_count { get; set; }
}
[WebMethod]
public static void GetTags()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["taggerConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetTagCount";
cmd.Connection = conn;
List<Tags> tag = new List<Tags>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
tag.Add(new Tags
{
tag_ID = sdr["tag_ID"].ToString(),
tag = sdr["tag"].ToString(),
total_count = sdr["total_count"].ToString()
});
}
}
conn.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string result = jSearializer.Serialize(tag);
System.Web.HttpContext.Current.Response.ContentType = "application/json";
System.Web.HttpContext.Current.Response.Write(result);
System.Web.HttpContext.Current.Response.End();
}
}
}
I guess I found the solution.
When I tried to troubleshoot using chrome's network tab..I got this result.
{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
From which I understood that its because of configuration in template
in App_Start/RouteConfig.cs this line:
settings.AutoRedirectMode = RedirectMode.Permanent;
In one of the post on SO (Authentication failed during call webmethod from jquery.ajx with AspNet.FriendlyUrls and AspNet.Identity)
it was suggested to comment it.
Now since this is done. Can any one suggest pros & cons of commenting out this line. If its not a good idea from security point of view, any workaround.?

View data using C# and JavaScript

I am using following JavaScript:
jQuery(document).ready(function ($) {
$(function () {
$.ajax({
type: "POST",
url: "candidate-job-alert.aspx/GetJobalerts",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
});
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
console.log(xml);
var customers = xml.find("Table");
console.log(customers);
var row = $("[id*=CandidateAlerts] tr:last-child").clone(true);
$("[id*=CandidateAlerts] tr").not($("[id*=CandidateAlerts] tr:first-child")).remove();
$.each(customers, function () {
var customer = $(this);
AppendRow(row, $(this).find("alert_name").text(), $(this).find("keywords").text(), $(this).find("job_location").text(), $(this).find("job_category").text(), $(this).find("job_type").text(), $(this).find("email_frequency").text())
row = $("[id*=CandidateAlerts] tr:last-child").clone(true);
});
}
function AppendRow(row, alertname, keyword, joblocation, jobcategory, jobtype, emailfrequency) {
//Bind alert_name.
$(".alert_name", row).find("span").html(alertname);
$(".alert_name", row).find("input").val(alertname);
//Bind keywords.
$(".keywords", row).find("span").html(keyword);
$(".keywords", row).find("input").val(keyword);
//Bind job_location.
$(".job_location", row).find("span").html(joblocation);
$(".job_location", row).find("input").val(joblocation);
//Bind job_category.
$(".job_category", row).find("span").html(jobcategory);
$(".job_category", row).find("input").val(jobcategory);
//Bind job_type.
$(".job_type", row).find("span").html(jobtype);
$(".job_type", row).find("input").val(jobtype);
//Bind email_frequency.
$(".email_frequency", row).find("span").html(emailfrequency);
$(".email_frequency", row).find("input").val(joblocation);
$("[id*=CandidateAlerts]").append(row);
}
This is my C# code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class candidate_job_alert : System.Web.UI.Page
{
string connectionString = ConfigurationManager.ConnectionStrings["JobMonsterConnectionString1"].ConnectionString;
string strg;
SqlCommand cms;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Email"] != null)
{
try
{
this.BindDummyRow();
//memberimg();
//lblRows.Text = getjobalerts();
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
}
private void BindDummyRow()
{
DataTable dummy = new DataTable();
dummy.Columns.Add("alert_name");
dummy.Columns.Add("keywords");
dummy.Columns.Add("job_location");
dummy.Columns.Add("job_category");
dummy.Columns.Add("job_type");
dummy.Columns.Add("email_frequency");
dummy.Rows.Add();
CandidateAlerts.DataSource = dummy;
CandidateAlerts.DataBind();
}
[WebMethod]
public static string GetJobalerts()
{
string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id = #CandidateId";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#CandidateId", Session["candidate_id"]);
string constr = ConfigurationManager.ConnectionStrings["JobMonsterConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
}
}
I am getting the following error:
Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get'
Line 55: string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id='" + Session["candidate_id"] + "'";
As mentioned in my comment, you need to use query parameterisation rather than concatenation otherwise you are open to a plethora of SQL Injection attacks.
The issue with your reference to Session is that your method is static, so you cannot access instance members (such as Session and anything else) of the System.Web.UI.Page. Make it an instance member instead of static should make your code work fine, I can't see any reason for it to be static, nor a POST request.
[WebMethod]
public string GetJobalerts()
{
string query = "SELECT alert_name, keywords, job_location, job_category, job_type, email_frequency FROM candidate_job_alerts where candidate_id = #CandidateId";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#CandidateId", Session["candidate_id"]);
// ..
}

ASP.NET ajax call using Jquery adds to list

I have a simple UI where I am trying to populate the select dropdown using data from database. I am doing this by a AJAX call to fetch the data.
The C# web method looks like
private static List<List<string>> componentTypeDropDown = new List<List<String>>();
private void loadDropDownList()
{
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}
[WebMethod]
public static ArrayList getComponentType()
{
ArrayList compType = new ArrayList();
for (int i=0;i<componentTypeDropDown.Count();i++)
{
compType.Add(new { label = componentTypeDropDown[i][0], value = componentTypeDropDown[i][1] });
}
return compType;
}
The AJAX call looks like
$.ajax({
type: "POST",
url: "salesQuote.aspx/getComponentType",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("karan");
},
error: function () {
alert("Failed to load names");
}
});
Every time I refresh or even restart the server the value of msg in success callback has previous values as well. For example lets say my database has value 1,2. First time I call ajax msg is 1,2 if i refresh the value is 1,2,1,2 and so on. Even if I close the server and start again the value would be 1,2,1,2,1,2
Your ComponentTypeDropdown is a static, so every time you call 'LoadDropdownList' this list will add new items, whitout removing the old ones.
I would suggest that you add following line in the loadDropDownList method:
private void loadDropDownList()
{
componentTypeDropdown.RemoveAll();
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}

Angular response appends object at the end

This is my POST request:
$scope.TestPost = function (par1, par2) {
$http.post('EmployeeService.asmx/GetAllEmployees',
{
par1: par1,
par2: par2
})
.then(function (response) {
$scope.employees = response.data;
})
};
And this is code that gets called on the server side. Code is called correctly and json serialized object is written to response:
[WebMethod]
public void GetAllEmployees(string par1, string par2)
{
List<Employee> listEmployees = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
List<Employee> _list = new List<Employee>();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Employee emp = new Employee
{
id = Convert.ToInt32(rdr["Id"]),
name = rdr["Name"].ToString(),
gender = rdr["Gender"].ToString(),
salary = Convert.ToInt32(rdr["Salary"])
};
listEmployees.Add(emp);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
Response object is this - some strange line is appended at the end {"d":null} which I can not understand why. I am also receiving error on the client side: SyntaxError: Unexpected token:
"[{"id":1,"name":"Ben","gender":"Male","salary":55000},
{"id":2,"name":"Sara","gender":"Female","salary":68000},
{"id":3,"name":"Mark","gender":"Male","salary":57000},
{"id":4,"name":"Pam","gender":"Female","salary":53000},
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}"
Thanks to #82Tuskers and this post:
Differences between Response.End() and Response.Flush()
I've found the solution. I've changed code at the end of server side function to:
Context.Response.Clear();
Context.Response.Write(js.Serialize(listEmployees));
Context.Response.Flush();
Context.Response.End();
Response is now OK.

Categories

Resources