I have a Jquery ajax function which makes call to a c# method. The function always returns null even when the string its supposed to return is in Json format. How do I get the return value in the Jquery function?
function GetScores() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetTopScores',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
alert(data.d); // Always NULL
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('ERROR!!');
}
});
}
public static string GetTopScores()
{
string result = string.Empty;
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=*****;Initial Catalog=beachlings;Persist Security Info=True;User ID=******;Password=******;MultipleActiveResultSets=True;Application Name=EntityFramework";
conn.Open();
string query = "Select TOP 20 PlayerName, SiteName, Score from HighScores ORDER BY SCORE DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
string s = JsonConvert.SerializeObject(rows);
return s;
}
}
catch (Exception ex)
{
return null;
}
}
Finally found what was causing the javascript to return null. I was calling GetTopScores() from within another method and instead of returning string I was returning void. Thanks for your help :)
Related
I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}
Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.
Is there a way that I can call my insert function from controller using my javascript from the view
Here is my controller:
public ActionResult Update(int a, string b)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = #a WHERE b = #b ", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#a", a);
cmd.Parameters.AddWithValue("#b", b);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return RedirectToAction("Index");
}
And here is my javascript that holds values from HTML
function SaveChanges() {
var a = document.getElementById("a").value
var b = document.getElementById("b").value
//TODO: pass the variables to the controller to perform insert query
}
Any suggestions or comments. TIA.
Please try this:
function submit(){
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
$.ajax({
url: '/ControllerName/Update(ActionResult)/'
type: 'post',
contentType: 'application/json',
data: {
'a':a,
'b':b
},
success: function(data){
alert('success');
},
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
}
}
});
What you want is using AJAX callback to call the controller action from client-side, which should be set up like example below:
JS function
function SaveChanges() {
// input values
// the variable names intentionally changed to avoid confusion
var aval = $('#a').val();
var bval = $('#b').val();
var param = { a: aval, b: bval };
$.ajax({
type: 'POST',
url: '#Url.Action("Update", "ControllerName")',
data: param,
// other AJAX settings
success: function (result) {
alert("Successfully saved");
location.href = result; // redirect to index page
}
error: function (xhr, status, err) {
// error handling
}
});
}
Then add [HttpPost] attribute to the controller action and return JSON data which contains URL to redirect, because RedirectToAction() does not work properly with AJAX callback:
Controller action
[HttpPost]
public ActionResult Update(int a, string b)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = #a WHERE b = #b ", con);
cmd.Parameters.AddWithValue("#a", a);
cmd.Parameters.AddWithValue("#b", b);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
// create URL and return to view
string redirectUrl = Url.Action("Index", "ControllerName");
return Json(redirectUrl);
}
Note that this is just a simple example, you can improve with try...catch exception handling and other things not mentioned here.
you should use jquery Ajax POST method for that . such as this structure...
function submit(){
var a = document.getElementById("a").value
var b = document.getElementById("b").value
$.ajax({
url: '/ControllerName/Update/'
dataType: 'text',
type: 'post',
contentType: 'application/json',
data: {
'a':a,
'b':b
},
success: function( data, textStatus, jQxhr ){
alert('success')
console.log(data)
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
Controller Code
public ActionResult Update(int a, string b)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = #a WHERE b = #b ", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#a", a);
cmd.Parameters.AddWithValue("#b", b);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return RedirectToAction("Index");
}
.cshtml Code
function SaveChanges() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
$.ajax({
type: 'GET',
url: '#Url.Action("Update")',
data: {
'a': a,
'b': b
},
success: function(result) {
alert("Successfully saved");
},
error: function(xhr, status, err) {
// error handling code
}
});
}
You need to call the SaveChanges() function on the submit button click event. Based on your reference code I have to make the method as GET, in case your method on controller side is POST, then in AJAX method you need to change method type GET to POST.
I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'
please rectify my corrections it not working i made a mistakes please rectify. i need html table based on selection. i tried but i cannot find any solution. i created drop down if i select any value in drop down & click button it display the selected table
var app = angular.module("myApp", []);
app.controller("myCntrl", function ($scope, $http) {
$("#Button1").click=function(RoleID){
var httpreq={
method:'POST',
url: 'WebForm1.aspx/getdata',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'dataType': 'json'
},
data: {}
}
$http(httpreq).success(function (response) {
$scope.RolesList = response.d;
})
};
<input id="Button1" type="button" class="button" value="button" ng-click="click()" />
public List<User> getdata(int RoleName)
{
string strConnection = "Data Source=192.168.1.42,1433;Initial Catalog=Harneedi;User ID=chaitanya_t;Password=makrotech";
List<User> userobj1 = new List<User>();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnection);
con.Open();
SqlCommand cmd = new SqlCommand("select userName,[RoleName],[status] from HN_Users_Details as t1 inner join HN_Master_User_Role as t2 on t1.RoleID=t2.RoleID where RoleName='"+RoleName+"'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
User userinfo = new User();
userinfo.UserName = dt.Rows[i]["UserName"].ToString();
userinfo.RoleName = dt.Rows[i]["RoleName"].ToString();
userinfo.status = dt.Rows[i]["status"].ToString();
userobj1.Add(userinfo);
}
}
return userobj1;
}
public class User{public string UserName { get; set; }public string RoleName { get; set; }public string status { get; set; }}
please rectify my corrections
Okay! Let's get to it.
You have this button in your current scope of work:
<input id="Button1" type="button" class="button" value="button" ng-click="click()" />
As i can see you are triggering the click() method defined in your controller's scope. so you have defined it badly i would say this don't mind. In my opinion you have to declare the method this way:
var app = angular.module("myApp", []);
app.controller("myCntrl", function ($scope, $http) {
$scope.RolesList = {}; // declare the role list here
$scope.click=function(RoleID){ // not sure how you pass this role id
var httpreq={
method:'POST',
url: 'WebForm1.aspx/getdata',
headers: {
'Content-Type': 'application/json; charset=utf-8' // this is useless it is default in angularjs
},
responseType: 'json', // use responseType instead of dataType
data: {}
};
$http(httpreq).then(function (response) { // ".success" is deprecated standard is set to use ".then()"
$scope.RolesList = response.d;
});
});
It would be nice if you can create a sample demo here #plnkr.
Though it is not clear exactly what your problem is, the basic understanding is that the code is not running properly, what I understand is, you have set your content type as json, but we are returning list from the getdata method.
So we need to serialize the data and return as json data.
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
And change the return type of the method as string, I suppose that would solve your problem.
I have a problem where I am getting an id from a selected checkbox, then it sends it to a delete method and it then passes the id to a stored procedure. The problem I am having though is it is returning my id in a wrong format ("232,4323") instead of ("232","4323") so when it comes to passing in values to the stored procedure, it craps out because of the string format.
Here is my code in the aspx.
function doTheDelete(doIDeleteTimeTracker) {
var selectedTimeTrackerList = getSelectedTimeTrackerIDs();
if (selectedTimeTrackerList.length > 0) {
$.ajax({
type: "POST",
//url: "/Tasks/ViewTasks.aspx/deleteTasksAndLinkedItems",
url: '<%=ResolveUrl("~/TimeTrackers/ViewTimeTrackers.aspx/deleteSelectedTimeTracker")%>',
data: "{'DeleteTimeTracker' : '" + doIDeleteTimeTracker + "'," + "'TimeBill': ['" + selectedTimeTrackerList.join(',') + "']}",
//dataaaaaa
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var ss = data.d;
if (ss.length > 0) {
for (var i = 0; i < ss.length; ++i) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true });
alert(ss[i]);
}
}
$("#viewTimeTrackersGrid").flexReload();
showMessage('Successfully Removed Time Tracker');
},
error: function (data) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true });
alert('Error Deleting Time Tracker');
if (window.console) {
console.log(data);
}
}
});
} else {
showMessage('No time tracker(s) are selected.');
}
}
and here is my delete method in the code behind.
public static string[] deleteSelectedExpense(bool DeleteExpenses, String[] ExpId)
{
var rList = new List<string>();
//var canDeleteTasks = false;
//var canDeleteTrackers = false;
var canDeleteExpenses = false;
var investigatorID = (int)HttpContext.Current.Session["InvestigatorID"];
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
var cmd = new SqlCommand("p_Admin_Permissions_CanDeleteExpenses", conn);
cmd.Parameters.Add(new SqlParameter("#InvestigatorID", SqlDbType.Int));
cmd.Parameters["#InvestigatorID"].Value = investigatorID;
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
canDeleteExpenses = (bool)cmd.ExecuteScalar();
}
catch (SqlException sql)
{
if (!rList.Contains("Can not connect to the database. Please try again."))
rList.Add("Can not connect to the database. Please try again.");
}
catch (Exception ex)
{
if (!rList.Contains("An Error Occured"))
rList.Add("An Error Occured");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
if (canDeleteExpenses)
{
foreach (var expense in ExpId)// expense ends up beng ("232,423") instead of just taking 1 string at a time ("232").....("423")...
{
if (canDeleteExpenses)
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
cmd = new SqlCommand("p_CaseFiles_Expenses_DeleteExpenses", conn);
cmd.Parameters.Add(new SqlParameter("#ExpID", SqlDbType.Int));
cmd.Parameters["#ExpID"].Value = int.Parse(expense);
cmd.Parameters.Add("#Message", SqlDbType.NVarChar, 50);
cmd.Parameters["#Message"].Direction = ParameterDirection.Output;
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException sql)
{
if (!rList.Contains("Error Connecting to the Database. Unable To Delete Expense(s)."))
rList.Add("Error Connecting to the Database. Unable To Delete Expense(s).");
}
catch (Exception ex)
{
if (!rList.Contains("An Error Occured"))
rList.Add("An Error Occured");
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
else if (!canDeleteExpenses)
{
rList.Add("You do not have permission to delete Expenses");
}
else
{
if (!rList.Contains("You do not have permission to delete the Expense(s)."))
rList.Add("You do not have permission to delete the Expense(s).");
}
}
}
return rList.ToArray();
}
I am guessing it could be in the "Data :" in the ajax call formatting for the array(I've tried a few things)
Try:
... 'TimeBill': ['" + selectedTimeTrackerList.join('","') + "']}" ...
Although a better solution would be to create a full javascript object with the required properties and apss it as an argument. BTW you may want to consider using something like PageMethods instead of jQuery if you are calling this method only on this page.
There is no reason to create a string to send as Data, you can send a json object instead.
Data: {
DeleteTimeTracker: doIDeleteTimeTracker,
TimeBill: selectedTimeTrackerList
}, ...
thanks for the help gents. I managed to fix it. Solution was to do this:
"'ExpId': ['" + selectedExpensesList.join('\',\'') + "']}",
instead of :
"'ExpId': ['" + selectedExpensesList.join(',') + "']}",
adding the extra ' seemed to work. It then manages to take each id seperately instead of taking the entire array and pooping on me