I have two classes: Person and account. Im working in asp net.
This is my controller:
public List<Person> GetPeople()
{
using (var db = new PeopleContext())
{
return db.People.ToList();
}
}
Person has the following attributes:
public class Person
{
public int PersonId{ get; set; }
public string Name{ get; set; }
public List<Accounts> Accounts{ get; set; }
}
Account class contains the following attributes:
public class Account
{
public int AccoundId{ get; set; }
public string AccountName{ get; set; }
public Person Person{ get; set; }
}
This is in my view
function getQuestions() {
$.ajax({
url: '/api/Person',
type: 'GET',
//dataType: 'json',
traditional: true,
success: function (data) {
$.each(data, function (i, p) {
string += '<h1>Name: '+p.Name+'</h1>';
$.each(p.Accounts, function (j, a) {
string += '<p>'+a.AccountName+'</p>';
});
});
},
});
How do i loop through account list in javascript and display it in my view? I have been trying to do this, but the list returns null. When i try to console log data it displays Accounts as null. How do i fix this?
I believe you would need to show your /api/Faq webservice response.
I would also suggest opening F12 developer tools and putting the word debugger in after you get the name:
string += '<h1>Name: '+p.Name+'</h1>';
debugger;
Then you can look at the p.Accounts object and see what it is.
If you Accounts object is empty you may need to add to your Person object's constructor:
public Person()
{
Accounts= new HashSet<Account>();
}
Related
Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
I know there are similar questions, but mine is just different enough to warrant me asking.
I'm trying to send a complex object via ajax to a .net MVC backend.
the receiving call is this:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult SaveLenderMemberSettings(List<AssignmentFeeRule> AssignmentFeeRules)
{
return Json(AssignmentFeeRules);
}
....
public class AssignmentFeeRule
{
public string Currency { get; set; }
public DateTime CutOffTimeBuy { get; set; }
public DateTime CutOffTimeSell { get; set; }
public int MinimumDaysToCloseBuy { get; set; }
public int MinimumDaysToCloseSell { get; set; }
public int OffsetDaysBuy { get; set; }
public int OffsetDaysSell { get; set; }
}
The call is getting invoked properly, but when I try and send the object, it's sent as the following:
AssignmentFeeRules[0][Currency]:AZN
AssignmentFeeRules[0][MinimumDaysToCloseBuy]:2
AssignmentFeeRules[0][MinimumDaysToCloseSell]:2
AssignmentFeeRules[0][OffsetDaysSell]:2
AssignmentFeeRules[0][OffsetDaysBuy]:2
AssignmentFeeRules[0][CutOffTimeBuy]:01:00
AssignmentFeeRules[0][CutOffTimeSell]:14:01
As a result of this code:
var assignmentFeeRule = {
Currency:$(tds[0]).find('select, input').val(),
MinimumDaysToCloseBuy:$(tds[1]).find('select, input').val(),
MinimumDaysToCloseSel":$(tds[2]).find('select, input').val(),
OffsetDaysSell:$(tds[3]).find('select, input').val(),
OffsetDaysBuy:$(tds[4]).find('select, input').val(),
CutOffTimeBuy:$(tds[5]).find('select, input').val(),
CutOffTimeSell:$(tds[6]).find('select, input').val()
};
assignmentFeeRules[rowCount - 1] = assignmentFeeRule
var data = {
AssignmentFeeRules : assignmentFeeRules
};
$.ajax({
url: url,
method: "POST",
data: data
}).done(function (data) {
console.dir(data);
}).fail(function (error) {
console.dir(error);
});
but I figured out that MVC needs it to be like this:
AssignmentFeeRules[0].Currency:AZN
AssignmentFeeRules[0].MinimumDaysToCloseBuy:2
AssignmentFeeRules[0].MinimumDaysToCloseSell:2
AssignmentFeeRules[0].OffsetDaysSell:2
AssignmentFeeRules[0].OffsetDaysBuy:2
AssignmentFeeRules[0].CutOffTimeBuy:01:00
AssignmentFeeRules[0].CutOffTimeSell:14:01
So far all my searches for an answer havn't turned up anything.
So basically, the bottom line is, how do I get this from an associative array a json object?
I have a game object in client side JavaScript that looks like this right before being sent to the server:
Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.
Here is the code for the models:
public class Game
{
public Game()
{
Questions = new List<Question>(5);
}
public int GameID { get; set; }
public Guid UserID { get; set; }
public Guid CurrentGameID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public IEnumerable<int> Answers { get; set; }
public int SelectedAnswer { get; set; }
}
And here is how I send the object back to the server:
// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
// display results to user
}
Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:
$.ajax(
{
url: "Games/CompleteGame",
type: "POST",
data: JSON.stringify(currentGame),
contentType: "application/json",
success: function (results)
{
// show results to user...
}
As it turns out, this was all it needed to make it work.
Here is a custom list (that I created for paging of my results):
public class PagedList<T> : List<T>
{
public int PageIndex { get; set; }
public bool HasNextPage { get; set; }
// ...
}
This list I want to pass via JSON to the View:
[HttpPost]
public ActionResult StoreProducts(StoreDetailsViewModel model)
{
PagedList<Product> products = _productRepository.GetAll();
return Json(products);
}
In the view I want to access to tho custom properties of my extended list but it's not working:
function getStoreProducts() {
var form = $('#form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
viewModel.products = result; // <-- success
viewModel.hasNextPage = result.HasNextPage; // <-- fail, property is undefined
}
});
}
Can somebody tell me how to solve my problem?
PagedList should be it's own class that has a property on it that is List, that's the easier route. Otherwise you'll need to write a custom converter for your PagedList class to not serialize as an array, but an object.
public class PagedList<T>
{
public int PageIndex { get; set; }
public bool HasNextPage { get; set; }
public List<T> Items { get; set; }
// ...
}
Not sure if it's just the time of day, lack of coffee or over indulgence of sugar from last night. Besides that I'm trying to get this working. I do not want to change / modify / add a new web service method.
I have an asmx web service:
public UserLogin Login(UserLogin p_objUserLogin)
{
}
I need to hook a JQuery ajax call up to that. The UserLogin object is not that complex:
public class UserLogin
{
public UserLogin();
public string Privileges { get; set; }
public string ClientCodeID { get; set; }
public UserDetails User { get; set; }
public string UserLoginMessage { get; set; }
public bool Valid { get; set; }
}
The UserDetails object is quite large, and includes a lot more data. (Hopefully I don't need to build the entire object tree to get this to work).
public class UserDetails
{
public string CellPhone { get; set; }
public string Email { get; set; }
public string EncryptedPassword { get; set; }
public string FirstName { get; set; }
public string FullName { get; }
public string Initials { get; set;
public bool InService { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public byte[] Signature { get; set; }
public string SimCard { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public SecurityRole UserSecurityRole { get; set; }
public Workgroup UserWorkgroup { get; set; }
}
The script I'm playing around with:
function CallService() {
var p_objUserLogin = {};
p_objUserLogin['ClientCodeID'] = "Test";
var DTO = { 'p_objUserLogin': p_objUserLogin };
$.ajax({
type: "POST",
url: "UtilityServices2006.asmx/Login",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + ", " + status + ", " + error);
},
complete: function (req, status) {
alert(req + ", " + status);
}
});
}
Any help would be quite amazing.
Ensure your webservice class and method are decorated to handle incoming ajax/json requests:
[ScriptService]
public class MyService: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UserLogin Login(UserLogin p_objUserLogin)
{
}
}
I'm not familiar with the notation you're using to configure your payload object (p_objUserLogin['ClientCodeID'] = "Test";). I've usually used slightly different notation:
p_objUserLogin.ClientCodeID = 'Test';
However, that might be a red herring - I'm not a JS-objects expert, so your notation may be perfectly valid.
Finally, I'm not sure if JS will automatically convert your object to JSON (var DTO = { 'p_objUserLogin': p_objUserLogin };). I use the json2 library to explicitly serialize JS objects to JSON:
var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };
Hope this helps you nail down the issue.