Reputation: 101
Im trying to display the data I retrieved from my Controller, and I can see the data on my Browser's console but it wont display in html. Here is my code:
function GetUserInfo() {
var username = readCookie("Cookie");
$.ajax({
url: '/api/getInfo/' + username,
type: 'GET',
data: { UserName: 'UserName', FirstName: 'FirstName', LastName: 'LastName' },
dataType: 'json',
success: function( Results ) {
if (Results.length > 0) {
$('#username').text(Results.UserName);
$('#firstname').text(Results.UserName);
$('#lastname').text(Results.UserName);
}
else {
alert( "No data." );
}
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
}
);
}
This is the data I need to display:
[
{
"Id": 0,
"UserName": "demouser",
"FirstName": "Demo",
"LastName": "User",
"EmailAddress": "[email protected]",
"PhoneNumber": "xxx-xxx-xxxx"
}
]
This is the server side code i use to display my data:
public List<Models.User> GetUserInfo( String username )
{
List<Models.User> UserInfo = null;
var Info = from m in db.MstUsers
where m.UserName == username
select new Models.User
{
UserName = m.UserName,
FirstName = m.FirstName,
LastName = m.LastName,
EmailAddress = m.EmailAddress,
PhoneNumber = m.PhoneNumber
};
UserInfo = Info.ToList();
return UserInfo;
}
How do I store the variables in the data option? What is the correct way to place data from an array? I am new to JQuery. Can someone tell me what's wrong with my code and help me understand the proper way to store data?
Upvotes: 1
Views: 1674
Reputation: 18576
As Results
is an array. You must either iterate and show the data in your DOM else use index Results[0]
(if its first element, change index based on the object you want to show) to show the results.
In case $("#username")
is an input text field, use $("#username").va(Results[0].username)
instead.
success: function( Results ) {
if (Results.length > 0) {
$('#username').text(Results[0].UserName);
$('#firstname').text(Results[0].UserName);
$('#lastname').text(Results[0].UserName);
}
else {
alert( "No data." );
}
}
Upvotes: 1