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.");
});
};
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.
In here I am able to display university images on dynamically created div. Now I want to get id of the university image which user selected, then use that id to display courses which selected university offer. Is there way to do that?
protected void fetchUniversities()
{
List<University> uniList = new List<University>();
using (var dd = new UniversityContext())
{
uniList = UniversityController.fetchUniversitiesOfferCourses(dd);
}
Literal header = new Literal();
header.Text = "<div class=\"container\"><div class=\"row\"><h2>Apply For University</h2><p>Select your preferred university</p></div></div>";
CompanyPanel.Controls.Add(header);
foreach (var item in uniList)
{
Literal label1 = new Literal();
label1.Text = "<div class=\"container\"><div class=\"row\" >";
Literal lblTwo = new Literal();
lable2.Text = "<img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/>";
Literal lblLast = new Literal();
label3.Text = "</div></div>";
Panel1.Controls.Add(label1);
Panel1.Controls.Add(label2);
Panel1.Controls.Add(label3);
}
}
You could achieve this in a better way by moving to a different framework and return data (e.g. JSON) in response to an ajax query (have a look at ASP.NET MVC).
Here is a way to achieve this using your example, it's a bit cumbersome and I haven't tested it but should get you in the right direction
Add a method as follows:
[WebMethod]
public static string GetUniversityCourses(int universityId)
{
List<UniversityCourses> courses = ...
StringBuilder coursesHtml = new StringBuilder();
foreach(var course in courses) {
//Generate your html here
coursesHtml.Append("<div>" + course.Name + "</div>";
}
return coursesHtml.toString();
}
Then add this javascript code to you aspx file:
function GetUniversityCourses(id) {
$.ajax({
type: "POST",
url: "Default.aspx/GetUniversityCourses",
data: {"id": id,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
$("#coursesContainer_" + id).html(jqXHR.responseText);
}
});
}
Then in your server side code:
lable2.Text = "<img src=\"/template/images/" + item.ImageName + "\" height=\"100%\"/><div id=\"coursesContainer_\"" + item.Id + "</div><script>$('a[data-getcourseid=\"" + item.Id + "\"]').on('click', function() { GetUniversityCourses(" + item.Id + ")}</script>";
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 am building a messaging area similar to facebook and I am using ajax with jquery and a asmx web service to serve the html to the client. My li click event works when the content is first loaded on page load using c#, but when ajax runs and refreshes the content from the web service the li event doesn't work anymore.
This an example of the html that is returned from the web service
<ol class="messagesrow" id="messages">
<li id="2345">
<div>Test Element</div>
</li>
</ol>
Web service markup
[WebMethod]
public string GetMessagesByObject(string id, string objectid, string userid, string timezone)
{
string output = string.Empty;
try
{
StringBuilder str = new StringBuilder();
DataSet results = results from store procedure
str.Append("<ol class=\"messagesrow\" id=\"messages\">");
for (int i = 0; i < results.Tables[0].Rows.Count; i++)
{
DataRow row = results.Tables[0].Rows[i];
DateTime date = Convert.ToDateTime(row["CreateDate"].ToString()).AddHours(Convert.ToDouble(timezone));
if (!TDG.Common.CheckStringForEmpty(row["ParentMessageID"].ToString()))
{
str.Append("<li id=\"" + row["ParentMessageID"].ToString() + "\">");
}
else
{
str.Append("<li id=\"" + row["MessageID"].ToString() + "\">");
}
str.Append("<div style=\"width:100%; cursor:pointer;\">");
str.Append("<div style=\"float:left; width:25%;\">");
if (!TDG.Common.CheckStringForEmpty(row["ImageID"].ToString()))
{
str.Append("<img src=\"/Resources/getThumbnailImage.ashx?w=48&h=48&id=" + row["ImageID"].ToString() + "\" alt=\"View Profile\" />");
}
else
{
str.Append("<img src=\"/images/noProfileImage.gif\" alt=\"View Profile\" />");
}
str.Append("</div>");
str.Append("<div style=\"float:left; width:75%; padding-top:4px;\">");
str.Append("<strong>" + row["WholeName"].ToString() + "</strong>");
str.Append("<br />");
if (row["BodyMessage"].ToString().Length < 35)
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString() + "</span>");
}
else
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString().Substring(0, 35) + "</span>");
}
str.Append("<br /><span class=\"smallGreyText\">" + String.Format("{0:g}", date) + "</span>");
str.Append("</div>");
str.Append("</div>");
str.Append("</li>");
}
str.Append("</ol>");
output = str.ToString();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
Jquery markup
$(document).ready(function () {
$("ol#messages li").click(function () {
var id = $(this).attr("id");
getMessage(id);
});
});
function getMessage(id) {
var timezone = $('#<%= hdfTimezone.ClientID %>').val()
var userid = $('#<%= hdfUserID.ClientID %>').val()
$.ajax({
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/GetMessage",
data: "{'id':'" + id + "','timezone':'" + timezone + "','userid':'" + userid + "' }",
success: function (data) {
$('#<%= hdfMessageID.ClientID %>').val(id);
$('#<%= ltlMessages.ClientID %>').html(data.d);
},
error: function (data) {
showError(data.responseText);
}
});
}
Since your list items are dynamic, you should delegate the event from the ol.
$(document).ready(function () {
$("#messages").delegate("li","click",function () {
getMessage(this.id);
});
});
The error you are getting ReferenceError: getMessage not defined shouldn't happen with the given code.
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; }