View data using C# and JavaScript - 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"]);
// ..
}

Related

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.?

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

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

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
}

how to know in wcf service in key/value pair

//IService.cs
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
String CheckAuth(String AccountID, String Password);
//Service.cs
public String CheckAuth(String AccountID, String Password)
{
String message="";
string StrCon = #"my conn string";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(StrCon);
string qry = "select * from Account where AccountID='" + AccountID + "' and Password='"+Password+"'";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
message = "Authorized";
}
else
{
message = "unauthorized";
}
con.Close();
return message;
}
i want to know that what does the variable d: stands for and how can i change the d: to Message:..??
i need some suggestion thank you..
//GETTING output
{
d: "Authorized"
}
//expected output
{
Message: "Authorized"
}
i m new to wcf so it will be helpful if i get undertandable suggestion
thank you..
The variable d is there for security reasons.
But you can always return an object instead of a string
public object CheckAuth(String AccountID, String Password)
{
// .. snip
return new {
Message = message
};
}
If you call your service like this, it should return something like
{
"d" : {
"Message": "Authorized"
}
}
Not sure what you're using on the front-end, if you use jQuery you could make a wrapper around the ajax function:
function doAjax(url, data, cb) {
$.ajax({
url: url,
data: data,
success: function(data) {
cb(data.d);
}
});
}
and make use of your new defined function like this:
doAjax('/CheckAuth', yourDataObj, function result(data) {
console.log(data.Message);
});

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources