Why does the data come back as undefined? - c#

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){

Related

Print value one by one from controller in asp.net MVC, when controller is called from ajax

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 + "&region=" + 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.

Get clicked image id on dynamic div

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>";

Passing a parameter through AJAX but displayed null in the MVC method

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.");
});
};

ReferenceError: getMessage not defined

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.

Passing parameter to controller function from jQuery function '$.ajax'

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.

Categories