'undefined' reported when bind gridview using AJAX in C# - javascript

I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.
Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.
Here is my code
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
}
},
failure: function () {
alert("error! try again...");
}
});
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
con.Open();
object val = cmd.ExecuteScalar();
return val == DBNull.Value ? "" : (string)val;
}

First of all
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
In this case you will have a single string.
Secondly beware of the name in your query leave it as schoolname not [School Name].
Then you have to Serialize into json and again parse into json in order to loop through objects.
Here is fully working code:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
data = JSON.parse(data.d);
for (var i = 0; i < data.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
}
},
failure: function () {
alert("error! try again...");
}
});
[WebMethod]
public static string GetGridData()
{
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
{
con.Open();
//object val = cmd.ExecuteScalar();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt); // fills data from select query
// return val == DBNull.Value ? "" : (string)val;
return JsonConvert.SerializeObject(dt);
}
}

Related

MVC Controller is not receiving the values that comes from the Ajax /Javascript script

I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff

Call Webmethod to Fill DropDownList

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.

How can i fill a DropDown list using ajax and a c# method

Hi my c# method is this:
[WebMethod]
protected static void fillList(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc)
{
int dato = 0;
string strSql;
dato = Convert.ToInt32(hiddenControl.Value);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
conn.Open();
strSql = "SELECT DISTINCT incid FROM HisReportes WHERE peri = " + dato;
SqlCommand camAND = new SqlCommand(strSql, conn);
System.Data.DataTable tablainc = new System.Data.DataTable();
camAND.CommandTimeout = 36000;
tablainc.Load(camAND.ExecuteReader());
foreach (DataRow dtrw in tablainc.Rows)
{
listinc.Items.Add(dtrw[0].ToString());
}
}
i tested with a onlick function and it works but i need to call it from Ajax function:
$.ajax({
type: "POST",
url: "Incio.aspx/fillList",
data: '{hiddenControl , listinc, dtrw }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
$.each(data, function (){
$("listinc").append($("<option />").val(this.incidente).text(this.dtrw[0]));
});
},
failure: function () {
alert("Failed!");
}
});
that's my ajax function but it is not filling the dropdown list.
you need to return the list from your WebMethod, I recommended you to return a string array from the WebMethod.
[WebMethod]
public static string[] fillList()
{
your code here....
return listinc.ToArray();
}
So, into Ajax in the success function
$.ajax({
type: "POST",
url: "./Inicio.aspx/fillList",
...
success: function (data) {
let data = data["d"];
let dropdown = $("#listinc");
for (let i = 0; i < data.length; i++) {
// put here your data
dropdown.append(`<option>${ data[i] }</option>`);
}
}
});

Native JS Ajax posted Object to ASP.Net is null

I've got working code in JQuery Ajax, however I've been told I have to use Native JS code to use it, and I'm not very familiar with using native JS for ajax, and most of the internet examples are basic ones. Basically, I have this object:
var Narudzba =
{
SifraNarudzbe: "AAA",
DatumNarudzbe: "",
Osigurano: document.getElementById("checkOsiguranje").value,
BrzaDostava: document.getElementById("checkBrza").value,
KlijentId: document.getElementById("klijentid").value,
Adresa: AdresaVar,
StatusNarudzbeID: 2,
Primaoc: PrimaocVar,
VrijemeIsporuke: null,
CijenaNarudzbe: UkupnaCijena,
NacinPlacanja: parseInt(document.getElementById("NacinPlacanja_Select").value)
};
Which I'm trying to post to my Controller. Here's how my working code in Jquery Ajax looks:
$.ajax({
url: "/klijentarea/klijent/SnimiNarudzbu",
data: Narudzba,
type: 'POST',
success: function (data) {
for (var i = 0; i < stavke_niz.length; i++) {
stavke_niz[i].NarudzbeId = parseInt(data);
}
stavke_niz = JSON.stringify(stavke_niz);
$.ajax({
url: "/klijentarea/klijent/SnimiStavke",
type: "POST",
dataType: "json",
data: stavke_niz,
contentType: 'application/json',
success: function (data) {
if (data === true) {
var id = document.getElementById("klijentid").value;
window.location.href = '/KlijentArea/Klijent?id=' + id;
}
}
});
}
});
Basically, it creates an order (Narudzba) with all sorts of details, posts it to this controller:
[HttpPost]
public int SnimiNarudzbu(Narudzbe Narudzba)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
Narudzba.SifraNarudzbe = finalString;
Narudzba.DatumNarudzbe = DateTime.Now;
ctx.Primaoci.Add(Narudzba.Primaoc);
ctx.Naruzbee.Add(Narudzba);
ctx.SaveChanges();
int newid = Narudzba.Id;
return newid;
}
Then I use the returned new ID, and assign it to all the objects inside stavke_niz, which is an array of order listings which gets created elsewhere in the code, and require OrderID before being added to database (I can add that code as well if necessary). Then the array with the updated OrderIDs gets sent to this controller:
[HttpPost]
public string SnimiStavke(IEnumerable<StavkaNarudzbe> stavke_niz)
{
if (stavke_niz != null)
{
ctx.StavkeNarudzbi.AddRange(stavke_niz);
ctx.SaveChanges();
return "true";
}
return "false";
}
Which successfully accepts the JSON posted with AJAX and adds the stuff to the database. Now, when I try to post in Native, like so:
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200 && this.readyState === 4)
{
alert(this.getAllResponseHeaders());
}
};
xhr.open('POST', '/klijentarea/klijent/SnimiNarudzbu', true);
xhr.send(Narudzba);
All of the values inside "Narudzba" are null, despite the object clearly having all the right values before being posted to controller. Help would be greatly appreciated.
You are missing Content-Type setting in your xhr request.
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
This should solve your problem.
Hope this helps!

Ajax request inside loop, page reload after completion

I m using Jquery ajax request inside loop, all goes well till the last request. but after last request, page automatically reloads.I m not being able to understand what is happening there.
Plz review and help.
I m using asp.net web form and web services for handling ajax request.
Jquery Code:
var mainData = GetFromExcel();
function StartSaving()
{
for (i = 0; i < totalCount; i++)
{
DoPost(i);
}
}
function DoPost(i)
{
var mainCode = MainData[i].MainCode;
var noOfAllot = MainData[i].NoOfAllotment;
var CompanyCode = MainData[i].CompanyCode;
console.log(mainCode +' Company Code:'+ CompanyCode+':' + noOfAllot);
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + CompanyCode + "'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
async: false ,
success: function (res) {
console.log(res);
},
error: function (res) {
}
});
}
GetFromExcel is function that takes excelsheet and convert into json array. for that i have used xlsx.js
WebServices Code:
[WebMethod]
public String DoAllotment(string MainCode, string sNoOfAllotment, string CompanyCode)
{
JavaScriptSerializer js = new JavaScriptSerializer();
if(checkData())
return "Error";
else
return "Success";
}
this is a common pitfall.
Modify your javascript method to return false, see below:
function StartSaving() {
for (i = 0; i < totalCount; i++) {
DoPost(i);
}
return false; //This is important for not allowing button click post back
}
In The asp.Net button add OnclientClick as shown below:
<asp:button ..... OnClientClick="return StartSaving();"></asp:button>
***Everything else is perfect in your code!!!!

Categories