Get Json Data from WebMethod to Application - c#

I wanted to get Json data from web method.In here i wanted to get News & Speaker both data but here only working News only.(Unable to get Speaker )
Here is my Stored Procedure
ALTER procedure [dbo].[LoadDayEvents]
#Date date
as
begin
select News,Speaker from Eventstbl
where DateToBePublished = CONVERT(date, #Date)
end
Here is my Web Method
[WebMethod, ScriptMethod]
public static string SelectEventDate(string date)
{
string News= "";
string Speaker = "";
try
{
SqlCommand comld = new SqlCommand("LoadDayEvents", conDB);
comld.CommandType = CommandType.StoredProcedure;
comld .Parameters.Add("#Date", SqlDbType.Date);
comld .Parameters["#Date"].Value = DateTime.Parse(date).Date;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
News = comld .ExecuteScalar().ToString();
Speaker = comld .ExecuteScalar().ToString(); // Thisone is not working
}
catch (Exception ee) { }
finally { conDB.Close(); }
return News;
}
Here i use Ajax/Json to get it
<script type="text/javascript">
$(document).ready(function () {
var urinews = '<%= ResolveUrl("WebMethods.aspx/SelectEventDate") %>';
var localtime = new Date();
var today = localtime.getFullYear() + '/' + (localtime.getMonth() + 1) + '/' + localtime.getDate();
$.ajax({
type: "POST",
url: urinews,
data: "{ date: '" + today + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#daily_news_Selection").append("<p>" + msg.d + "</p>");
},
error: function (x, e) {
}
});
});
</script>

You could return custom class
var newsAndSpeaker = new NewsAndApeaker() { News = News, Speaker = Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables using
msg.d.News //news
msg.d.Speaker
Or, you could return a list of string
var newsAndSpeaker = new List<string>() { News, Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables as in like a array
msg.d[0] //mews
msg.d.[1] //speaker
If your question is why your second property is not getting populated, then title seems to be wrong

Related

Loading data into html table using ajax and SQL stored procedure

I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.
Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.

Error 500 for retrieved Json img src from database

I try to display image retrieved from db with some other object values as Json.
I learned that image object is not json serializable, so I changed byte[] to string in class, and pass it as image source.
Ajax POST response, should show image where I call its src src=\"'+photo+'"\"/> in JQuery. When I run the page, I receive Error 500 Internal Server Error in Browsers Console.
Class:
//other class values
public string Photo { get; set; }
[WebMethod]
public static string GetRooms(string arrival, string departure, string nob)
{
//db connection
SqlDataReader sdr = cmd.ExecuteReader(); ;
while (sdr.Read())
{
Room r = new Room();
//other values
b = (byte[])sdr["Photo"];
r.Photo = "data:image/jpg;base64," + Convert.ToBase64String(b).ToString();
lst.Add(r);
val = jSerialize.Serialize(lst);
}}
 
}
return val;
Ajax:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "main.aspx/GetRooms",
data: "{'arrival':'" + arrival + "','departure':'" + departure + "','nob':'" + nob + "'}",
dataType: "json",
success: function (response) {
r = jQuery.parseJSON(response.d),
$.each(r, function (k) {
var id = this.ID,
title = this.RoomTitle,
price = this.Price,
photo=this.Photo,
divItem.append($('<div />', { "class": "row" }).append($('<img src=\"'+photo+'"\"/>', { "class": "h-looks-s" })),
//other values appended
);
});
},
error: function (result) {
alert("Failed!");
}
Thanks for your help.

Populate items in dropdownlist

I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},

passing string array from ajax to c# web method

Hi I have this code below
How could I pass preferably 1 array which will contain an ID number and a value from a textbox which is dynamically generated and then passed to the backend to C#
var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
listoftextboxesWithID[i] = value.ID.toString();
listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
i++;
});
//---Till here the data in the above arrays is as expected, the problem starts below in the data :
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
[WebMethod]
public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity,
string supplier, float vatRate, int colorID, int brandID, string imagePath, string[] listOfTextBoxesID, string[] listOfTextBoxesValues )
{
Product p = new Product();
ProductPriceType ppt = new ProductPriceType();
p.CategoryID = subCategoryID;
p.Name = name;
p.Description = description;
p.Quantity = quantity;
p.Supplier = supplier;
// p.VATRate = vatRate;
p.ColorID = colorID;
p.BrandID = brandID;
p.Image = imagePath;
//...
}
Any help would be much appreciated
if I will do it, my approach is to seperate those two,
create string array for texts
create string array for values
i believe that the number of values will be the same with texts since it is generated dynamically.
then pass those two string arrays in c# backend.
you can use json2.js is cool ,I used this
var valueObj = { field1: $("input[name=field1]").val(),
field2: $("input[name=field2]").val()}
and then I can parse with this:
JSON.stringify(valueObj)
in the ajax call you can use like this
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data:valueObj ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
//In JS file
var arr = [];
arr.push( $("#textZipcode").val());
arr.push( $("#textPhone").val());
arr.push($("#textAddress").val());
arr.push( $("#textMobile").val());
//You can add any number. It will store to array properly.
$.ajax({
type: "POST",
url: "HomePage.aspx/SaveData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({arr:arr}),
success: function (response) {
}});
//In C#
[WebMethod]
public static void SaveData(string[] arr)
{
}

jquery ajax not returning data on success c# asp.net

I cant for the life of me figure out why my data being returned is empty. In fiddler i see the json
d=[{"response":[{"h":"h1"},{"h":"h1"}] }]
in fiddler there is a 200 status on the row where i see the json, but no other rows after that one ( maybe its not returning? ). This is the code i am using
$('.SomeLink').click(function () {
var sfn = $('#ID1').val();
var sfp = $('#ID2').val();
var sfi = $('#ID3').val();
var gid = $('#ID4').val();
$.ajax({
type: "POST",
cache: false,
url: '/AjaxHandler.aspx/GetNewHtml',
contentType: "application/json; charset=utf-8",
data: "{'a':'" + sfn + "','b':'" + sfp + "','c':'" + gid + "','d':'" + sfi + "'}",
dataType: "json",
success: function (data) {
alert(data.response[0].h); //acts like a syntax error/no alert box
alert(data); // [object Object]
alert(data.response); // undefined
alert(data.response.count); //acts like a syntax error/no alert box
},
error: function (e) {
alert("Error: " + e.responseText);
}
});
});
AjaxHandler.aspx
[System.Web.Services.WebMethod()]
public static string GetNewHtml(string a, string b, string c, string d)
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "h1"},
new Samp{h = "h1"}
};
return Serialize(new { response = samp });
}
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
Samp Class
public class Samp
{
public string h = "";
}
This is my first time using jquery ajax with asp.net so im sure im missing something that is probably relatively simple. Im using .Net 4.0 , jquery 1.7.1 , iis 7.5
Try data.d for your return object:
alert(data.d);
its tripping over the quotes around the property names. try string indexes.
try
data["response"][0]["h"]
returns h1

Categories

Resources