Invoke Server Methods From Client Side Using jQuery AJAX in ASP.NET - c#

I have to call server side method update(input parameters) by using ajax call.when I am running the code my ajax is not loading.I want to update that data to Jquery Data table.please give me suggestions
$(document).on('click', '#btnsave', function () {
//have to get the emp_id
var id = $('#hdnid').val();
update(id);
});
function update(id) {
var name = $('#txtempname').val();
var sal = $('#txtsal').val();
var Dept_Id = $('#ddllist').val();
$.ajax({
//var Data = "{ empname:" + name + "}";
url: 'jdatatable.aspx/update',//my .aspx page name
type: "POST",
data: '{ id: ' + id + ',empname: "' + name + '", sal: ' +sal + ', Dept_Id: ' + Dept_Id + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (data) {
alert("successfully done");
table.ajax.reload();
$('#txtempname').val('');
$('#txtsal').val('');
$('#ddllist').val('');
},
"error": function (data, xhr, status) {
alert(status);
}
});
jdatatable.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
//mymethod
[System.Web.Services.WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public void update(int id, string empname, int sal, int Dept_Id)
{
string s = ConfigurationManager.ConnectionStrings["dbconn"].ToString();
List<UserDetails> li = new List<UserDetails>();
SqlConnection con = new SqlConnection(s);
con.Open();
SqlCommand cmd = new SqlCommand("sp_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", id));
cmd.Parameters.Add(new SqlParameter("#Emp_Name", empname));
cmd.Parameters.Add(new SqlParameter("#Sal", sal));
cmd.Parameters.Add(new SqlParameter("#Dept_Id", Dept_Id));
cmd.ExecuteNonQuery();
con.Close();
}

Related

How to dynamicallly populate selectize using c# webmethod

I am using https://selectize.github.io/selectize.js/
and I've followed their example for dynamic population
in my aspx page I have
$('#stationid').selectize({
valueField: 'value',
labelField: 'text',
searchField: ['text'],
create: function (input, callback) {
$.ajax({
url: 'Search.aspx/GetListboxValues',
data: "{'query':'" + input+ "'}",
type: 'POST',
dataType: 'json',
success: function (response) {
return callback(response);
}
});
},
render: {
option: function (item, escape) {
return '<div>' + escape(item.text) + '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
type: "POST",
url: "Search.aspx/GetListboxValues",
data: "{'query':'" + query + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
error: function () {
callback();
},
success: function (res) {
callback(res);
}
});
}
});
<asp:ListBox ID="stationid" Width="300" SelectionMode="Multiple" runat="server">
</asp:ListBox>
In my aspx.cs I have
[WebMethod]
public static string GetListboxValues(string query)
{
string _conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string sql = "select station_name as [value], station_name as [text] from station where station_name like '%" + query + "%' group by station_name order by station_name asc";
cmd.CommandText = sql;
con.Open();
DataTable dt = new DataTable();
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return JsonConvert.SerializeObject(dt);
}
The webmethod works and returns a json in the following format
{"d":"[{\"value\":\"I-M-987\",\"text\":\"I-M-987\"},{\"value\":\"S-2987\",\"text\":\"S-2987\"},{\"value\":\"S-987\",\"text\":\"S-987\"}]"}
If I type in the listbox then selectize adds what I'm typing and fires off the webmethod but the listbox is not populating with the returned json values. How can I solve this ? Thank you in advance!
in case anyone else has this issue, the freaking problem was the json was formatted wrong.
I needed to use eval function to get only text from json, because raw json had all those \"
so just do this
success: function (res) {
var rspns = eval(res.d);
callback(rspns);
}

Failed to load WebMethod

My drop down change function works good. But the WebMethod failed to load
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("[id*=drpSub]").change(function () {
var drpSub = $("[id*=drpSub]").val();
var Gs_Id = $("[id*=ddlClass]").val();
alert(drpSub);
$.ajax({
type: 'GET',
url: 'assignments1.aspx/GetAssignmentType',
data: {},
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//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']));
//});
}
});
});
});
Code Behind
[WebMethod]
public static List<ListItem> GetAssignmentType()
{
string query = "SELECT OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type + ' (' + CONVERT(varchar(10), COUNT(8)) + ')' AS AT_Type FROM OP_Assignments INNER JOIN OP_AssignmentType ON OP_Assignments.OP_AS_TypeId = OP_AssignmentType.AT_Id WHERE (OP_Assignments.OP_AS_SubjId = '" + 10 + "') AND (OP_Assignments.OP_GS_IdNo = 37) And OP_AS_LastDate>='" + DateTime.Now + "' GROUP BY OP_AssignmentType.AT_Id, OP_AssignmentType.AT_Type";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> customers = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["Sub_Id"].ToString(),
Text = sdr["Subject_Name"].ToString()
});
}
}
con.Close();
return customers;
}
}
}
I know code inside the web method may be wrong. My actual problem is, the page is not loading when in put break point in the web method code behind. My console is error free. Is their any fault in my jQuery. Please Help
You have to add contentType: "application/json; charset=utf-8", in your ajax so, your ajax would be like
$.ajax({
type: 'GET',
url: 'Default.aspx/GetAssignmentType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (r) {
//var ddlCustomers = $("[id*=drpType]");
//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']));
//});
}
});

How to create dependency dropdownlist in ajax

I use below code .I have 2 dropdownlist it work fine.but problem is second drodownlist value doesnt store in database when i click on update button.It gives null value reference unhandled error.On form.aspx.cs i take that value on label cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString()); but in this it takes null value
<script type="text/javascript">
$(function() {
//$('#<%=DropDownList2.ClientID %>').attr('disabled', 'disabled');
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$('#<%=DropDownList1.ClientID %>').change(function() {
var country = $('#<%=DropDownList1.ClientID%>').val()
$('#<%=DropDownList2.ClientID %>').removeAttr("disabled");
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'country':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
},
error: function(data) {
alert('Something Went Wrong')
}
});
});
$('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
$("#DropDownList2").children("option").is("selected").text()
$('#<%=DropDownList2.ClientID %>').change(function() {
var stateid = $('#<%=DropDownList2.ClientID%>').val()
var myVar =('#DropDownList2').find(':selected').text();
$.ajax({
type: "POST",
url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
data: "{'state':'" + post_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=DropDownList2.ClientID %>').html(options)
$("option:selected", myVar).text()
},
error: function(data) {
alert('Something Went Wrong')
}
});
})
})
</script>
and my c# code is
private void Bindcategorydown()
{
String strQuery = "SELECT [dept_no],[department_name] FROM [first].[dbo].[dept_add]";
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "department_name";
DropDownList1.DataValueField = "dept_no";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Department", "0"));
con.Close();
}
}
}
[WebMethod]
public static string BindPosts(string country)
{
StringWriter builder = new StringWriter();
String strQuery = "SELECT [post_id],[post_name] FROM [first].[dbo].[add_post] where group_id=#dept_no";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("#dept_no", country);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["post_name"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["post_id"] + "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}
and on update button i use this
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#department", DropDownList2.SelectedItem.Text);
If the problem persists, send us the stack trace of the error.

System.InvalidOperationException: Missing parameter

I try to send parameter to asmx(web service file) but i get error about "System.InvalidOperationException: Missing parameter". Please help me to solve this problem and thank you so much
this is my ajax function
$("#dd_address").change(function () {
var rowID = $(this).find(':selected').val();
console.log(rowID);
$.ajax({
url: "WebService.asmx/queryCity",
data: {
id: JSON.stringify(rowID),
},
type: "POST",
dataType: "json",
contentType: "application/json; charset-utf-8",
success: OnSuccess,
error: OnError
});
});
this is my code from asmx
DataTable result;
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string queryCity(string id)
{
DataTable dt;
SqlConnection MRK_Conn = new SqlConnection(#"Data Source=192.168.24.30;Initial Catalog=Marketing_Data;Persist Security info=True;User ID=sa;Password=sa");
SqlCommand cmd = new SqlCommand();
SqlDataReader sql_dr;
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
MRK_Conn.Open();
cmd = new SqlCommand("select [City RowID], [City Description] from City where [Des Ref Province] = '" + id + "'", MRK_Conn);
dt = new DataTable();
sql_dr = cmd.ExecuteReader();
dt.Load(sql_dr);
sql_dr.Close();
MRK_Conn.Close();
result = dt;
return serializer.Serialize(result);
}
and in web config file
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Problem in your code is in the way you are passing the input parameter to the method, change it like this:-
var rowID = { "id" : $(this).find(':selected').val() };
Then, pass it like this in the method:-
data : JSON.stringify(rowID)
Apart from this your ADO.NET code is open for SQL Injection attack, so please use parametrized query instead.
I have updated your code, below code works for me. Please remember I have hardcoded var rowID = 20; make your changes as you need.
Please let me know if you have any questions.
ASPX Page button:
<input type="button" value="submit" onclick="sendrequest();" />
Javascript "sendrequest" Function:
<script>
function sendrequest()
{
var rowID = 20;
console.log(rowID);
$.ajax({
url: "WebService.asmx/queryCity",
data: '{"id":"' + rowID + '"}',
type: "POST",
dataType: "json",
contentType: "application/json; charset-utf-8",
success: function (data) {
var xmlDoc = $.parseXML(data.d);
var xml = $(xmlDoc);
var city = xml.find("Table1");
alert(city.text());
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error: ' + xhr.status + ' ' + thrownError);
}
});
}
</script>
Webservice Method:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string queryCity(string id)
{
DataSet ds = new DataSet();
DataTable dt= new DataTable("Table");
SqlConnection MRK_Conn = new SqlConnection(#"Data Source=KEVAL;Initial Catalog=SampleDatabase;Persist Security info=True;User ID=sa;Password=sa123");
SqlCommand cmd = new SqlCommand();
SqlDataReader sql_dr;
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
MRK_Conn.Open();
cmd = new SqlCommand("select [City RowID], [City Description] from City where [Des Ref Province] = '" + id + "'", MRK_Conn);
dt = new DataTable();
sql_dr = cmd.ExecuteReader();
dt.Load(sql_dr);
sql_dr.Close();
MRK_Conn.Close();
ds.Tables.Add(dt);
return ds.GetXml();
}

Serialize List in a WebService to Json and pass to ajax on load

I am trying to pass a list that is populated by the database in a Web Service to ajax using JSON. However, I'm not sure what I'm missing and where to go from here.
Web Service
public class RetrieveWidgets : System.Web.Services.WebService
{
[WebMethod]
public static RetrieveWidgetsDAL[] GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> GetWidgetList = new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
GetWidgetList.Add(widgetDAL);
}
}
//trying to serialize GetWidgetList to JSON
var js = new JavaScriptSerializer();
var strJSON = js.Serialize(GetWidgetList);// not sure if this is the correct way?
}
conn.Close();
return GetWidgetList.ToArray();
}
}
Data Structure class
public class RetrieveWidgetsDAL
{
public string Title { get; set; }
public int SortNo { get; set; }
public int Collapsed { get; set; }
public int ColumnId { get; set; }
}
ajax
$(document).ready(function () {
if ($.cookie('modal_shown') == null) {
$.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
$('#popup').dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
data: <---don't know how to get the data,
dataType: "json",
success: function (response) {
alert(data);
}
});
}
});
I'm new to the idea of JSON so I'm still struggling to learn it. Any help is greatly appreciated.
EDIT: This is what I receive now on error in the browser console..
EDIT 2: I've removed static from my webservice..
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<RetrieveWidgetsDAL> GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> lstData = new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
lstData.Add(widgetDAL);
}
}
}
conn.Close();
return lstData;
}
Now my console shows [object Object]
Edit 3: I used the solution that has the accepted answer, however.. had to fix the ajax..
contentType was missing a ;
contentType: "application/json; charset=utf-8"
and now it alerts on the success!
Try this
[WebMethod]
public static List<RetrieveWidgetsDAL> GetWidgets()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
List<RetrieveWidgetsDAL> lstData= new List<RetrieveWidgetsDAL>();
int getUserId;
string userName = HttpContext.Current.User.Identity.Name;
conn.Open();
using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdGetUserId.Parameters.AddWithValue("#UserName", userName);
getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
}
using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = #UserId", conn))
{
cmdGetWidgets.Parameters.AddWithValue("#UserId", getUserId);
using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
{
while (rdr.Read())
{
RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
widgetDAL.Title = rdr.GetString(0);
widgetDAL.SortNo = rdr.GetInt32(1);
widgetDAL.Collapsed = rdr.GetInt32(2);
widgetDAL.ColumnId = rdr.GetInt32(3);
lstData.Add(widgetDAL);
}
}
}
conn.Close();
return lstData;
}
}
JS: On success use response.d
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
dataType: "json",
success: function (response) {
alert(response.d); // try using response.d
},
error:function (repo){
console.log(repo);
}
});
First of all, you need to change your webserver return:
public class RetrieveWidgets : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static RetrieveWidgetsDAL[] GetWidgets()
{
//...
}
}
Then change your jquery:
$.ajax({
type: "Post",
contentType: "application/json charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
cache: false,
dataType: "json"
})
.done(function( data ) {
alert(data);
});

Categories

Resources