I have a web Method in my C# that is called via Jquery ajax method. The web method should return an object back to the Jquery which will be used to populate.
I have tried returning a JsonResult object, the actual object and nothing seems to work! I'm not using MVC (Unfortunately). Is there a way that I can return an object from my web method which can be used by my AJAX method?
here is the link for my JQuery AJAX method
http://pastebin.com/tRSaY5rG
http://pastebin.com/WajXyPMM
Thanks!!
I have used JQuery to get results from a database and populate a UL on a page with the items. Is this what you were looking for?
Javascript
//Set up Approve Requests Page
$("#approveRequests").bind('pageAnimationEnd', function () { getRequestList(); return false; });
//Gets the list of requests
function getRequestList() {
// call server-side webmethod using jQuery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetOrdersForApproving",
data: "{ }", // send an empty object for calls with no parameters
dataType: "json",
success: displayRequests,
failure: reportError
});
}
//displays the requests in the ul
function displayRequests(result) {
// ASP.NET encapsulates JSON responses in a property "d"
if (result.hasOwnProperty("d")) { result = result.d; }
// iterate through player list and add info to the markup
var ul = $("#requestsForApproval");
for (i = 0; i " + result[i].Supplier + "," + result[i].Description + "," + result[i].Value + "");
var li = $(""
+ "" + result[i].OrderID + " - " + result[i].Supplier + ""
+ ""
+ ""
+ result[i].Description
+ ""
+ " "
+ ""
+ ""
+ ""
+ "Quant: " + result[i].Quantity
+ ""
+ ""
+ "Price: " + result[i].UnitPrice
+ ""
+ ""
+ "Total: " + result[i].Value
+ ""
+ ""
+ ""
+ ""
+ " "
+ "Approve"
+ "Reject"
+ ""
+ ""
+ "");
ul.append(li);
}
ASPX
///
/// Gets a list of Request Lines
///
/// List of order lines
[WebMethod]
public static List GetOrdersForApproving()
{
try
{
List Lines = new List();
foreach (Objects.Database.OrderLine oOrderLine in Objects.Database.OrderLine.GetLinesWaitingFor(StaticStore.CurrentUser.UserID, int.MinValue))
{
Lines.Add(new iOrderLine(oOrderLine));
}
return Lines;
}
catch (Exception)
{
throw;
}
}
The bit that code me struggling to get this working was:
if (result.hasOwnProperty("d")) { result = result.d; }
Related
I have a AJAX call for controller as below,
function print(response, endpoint) {
$(".tt").append("<tr><td>" + JSON.stringify(response[0], null) + "</td><td>" + JSON.stringify(response[1], null) + "</td><td>" + JSON.stringify(response[2], null) + "</td><td>" + JSON.stringify(response[3], null) + "</td><td>" + JSON.stringify(endpoint, null) + "</td></tr>");
}
$(".submit").click(function () {
var env = $("#env").find(":selected").text();
var region = $("#region").find(":selected").text();
var country = $("#country").find(":selected").text()
var folderPath = $.trim($('#folderPath').val());
var ajaxRequest = $.ajax({
contentType: "application/json ;charset=utf-8",
type: "GET",
async: false,
url: "/Home/GetmyModel" + "?selcetion=" + env + "®ion=" + region + "&country=" + country + "&folderpath=" + folderPath,
success: function (response) {
if (response != null) {
//print(response, endpoints[i]);
}
},
error: function (exception) {
},
complete: function (data) {
}
});
My controller goes like this
public void GetmyModel(string selcetion, string region, string country, string folderpath)
{
foreach (var item in System.IO.File.ReadLines(folderpath))
{
//do some work with return value as list<string>
//show list<string> in table in view using either print method of JS or by another way
}
}
Everything works fine if i send complete response back by making return type as JsonResult. However i am not understanding how can i print each item.
I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){
I new with MVC and I'am trying to display a method with AJAX. The problem is that the parameter that I am passing into the method is display to be null, but when I debug the ajax code the parameter is not null. I don't know what I'm doing wrong.
This is my c# method
public JsonResult AllAccountList(int accountID)
{
Client myClient = new AccountServiceClient().GetClientByUsername(System.Web.HttpContext.Current.User.Identity.Name);
IEnumerable<Account> myAccounts = new AccountServiceClient().GetAccountWithClient(myClient.ClientID);
List<AccountModel> myList = new List<AccountModel>();
foreach (Account a in myAccounts.Where(a => a.AccountID == Convert.ToInt32(accountID)))
{
myList.Add(new AccountModel() { AccountID = a.AccountID,TypeID_FK = a.TypeID_FK, FriendlyName = a.FriendlyName, Currency = a.Currency, AvailableBalance = a.AvailableBalance});
}
return Json(myList, JsonRequestBehavior.AllowGet);
}
and this is my AJAX
function btnSelectClicked(AccountID) {
var params = '{"accountID":"' + AccountID + '"}';
$.ajax({
type: "POST",
url: "/Account/AllAccountList",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
},
error: function (xhr,err) {
alert(xhr.responseText + "An error has occurred during processing your request.");
}
});
};
Try changing
var params = '{"accountID":"' + AccountID + '"}';
to
var params = {accountID: AccountID };
And see if that helps
UPDATE:
I didn't expect that to complain about a function... granted when ever I use the jquery ajax methods I use the specific one I need rather than the root ajax() method. Try this maybe.
function btnSelectClicked(AccountID) {
var params = {accountID: AccountID };
$.post("/Account/AllAccountList", data, function(data) {
var gridview = "<table>";
gridview += "<tr><td id='titleCol'>AccountId</td><td id='titleCol'>Account Type</td><td id='titleCol'>Friendly Name</td><td id='titleCol'>Currency</td><td id='titleCol'>Available Balnce</td></tr>";
for (var i = 0; i < data.length; i++) {
gridview += "<tr><td>" + data[i].AccountID +
"</td><td>" + data[i].TypeID_FK +
"</td><td>" + data[i].FriendlyName +
"</td><td>" + data[i].Currency +
"</td><td>" + data[i].AvailableBalance + "</td></tr>";
}
gridview += "</table>";
$("#display2").html(gridview);
});
})
.fail(function(jqXHR, textStatus, errorThrown ){
alert(jqXHR.responseText + "An error has occurred during processing your request.");
});
};
I've a dynamically created HTML table in the Server side code(using C#). When i pass that to client site using JASON. I couldn't able to receive that code in the client site. this is my code in the Server Side.
$.ajax({
type: "POST",
url: "ExcelUpload.asmx/UploadFile",
data: JSON.stringify({ XML: XMLDoc}),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#Status").html("<br><center><img src='ajax-loader.gif'/></center>");
},
success: function (result) {
var output = "";
var re = eval('(' + result.d + ')');
if (re.length > 0) {
for (var i in re) {
var xl = re[i];
switch (parseInt(xl.status)) {
case 1: { output = xl.message; break; }
case 2: { output = xl.message; break; }
}
}
$("#Status").html(output);
}
},
error: function (result) {
$("#Status").addClass("error");
$("#Status").html(result.d);
}
});
In that server side code I'm generating the HTML table using this code
HTML += "<table id='excelDoc'>";
HTML += "<tr><th>Date</th><th>Description</th><th>Reference</th><th>Nominal Code</th><th>Dept Code</th><th>Debit</th><th>Credit</th></tr>";
HTML += "<tr><td>" + eDoc.posting_Date.ToShortDateString() + "</td><td>" + eDoc.Description + "</td><td>" + eDoc.Ref_Number + "</td><td></td><td></td><td class='db'></td><td class='cr'></td></tr>";
HTML += "";
status = "{status : 1 , message : " + HTML + "}";
return " ["+ status+ "]";
Please Help me.
why are you doing result.d ?
Should it not be simply result ?
1 thing I notice more, in your AJAX request, your
dataType: "json"
but you are returning a simple string. Change to
dataType:"text"
and then try returning the string. It would def work
I am using ASPNET MVC 2.0. I'm trying to pass a value from View to Controller function using jquery function .ajax. My jquery function is:
$(document).ready(function() {
$("#Search").click(function(event) {
var searchString = $("#TraderSearch").val();
$.ajax({
type: 'POST',
url: '/Build/SearchTrader',
data: "{strData : '" + searchString + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(ResultList) {
var contents = "";
var count = 0;
$(ResultList).each(function() {
contents = contents + '<tr><td>' + ResultList[count].Name + '</td><td>' + ResultList[count].Value +
'</td><td><a class="edit"><img src="../../html/images/Edit.gif" width="14" height="14" alt="edit" /></a></td></tr>';
count = count + 1;
});
$("#SerachResultList").append(contents);
alert("{strData : '" + searchString + "' }");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + "\n" + errorThrown);
}
});
});
});
And my Controller function is as follows:
public ActionResult SearchTrader(string strData)
{
//Function to search DB based on the string passed
return Json(lstDictObject);
}
My problem is that, I am not able to get the value in my controller. I'm getting strData as 'null'. I think there is somme mistake in the way i'm trying to pass the value? Can anyone correct me?
Thanks in Advance,
Vipin Menon
try this:
data: "strData = " + searchstring
I believe the following should work:
data: { strData: searchstring }
Quotes caused the same issue in the script I just tested.
You also need to check the spelling on your "#SerachResultList" if this is your actual code.