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; }
// ...
}
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 generate the js object, which looks as follows:
cartStorage = {
name: 'testcustomer',
email: 'test#gmail.com',
items: [
{
licenseName: 'Private',
licensePrice: 2
},
{
licenseName: 'Public',
licensePrice: 4
}
],
totalPrice: 6
}
Then I pass this object to mvc controller using ajax
$.ajax({
url: '/TestPayment/ChargeTest',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(cartStorage),
success: function(response){
if (response != null) {
alert(response);
} else {
alert("Something went wrong");
}
}
});
Here's the viewmodel associated with this method
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public Items Items { get; set; }
}
}
Here's the mvc controller method, which processes the ajax request
[HttpPost]
public ContentResult ChargeTest([FromBody] PayerInfo model)
{
String FullName = model.name;
}
But when the server executes the controller method, the model turns out to be null.
However, if I comment out the Items class and the instance creation in the PayerInfo class in the viewmodel, then the model is being forwarded successfully and all the data is stored, I'm just having the problem with the list inside of js object.
What am I doing wrong?
items in your json object is a list. So you need to change the type of Items in your c# model to a list.
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public List<Items> Items { get; set; }
}
}
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>();
}
In my view I have a form with few fields. For model ID I have
#Html.HiddenFor(model => model.id)
The model is passing to controller with ajax
function submitDocument() {
$.ajax({
url: "/Documents/Save_Document",
type: "post",
data: JSON.stringify($("#form").serialize()),
success: function (data) {
// ... some code goes here
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
The controller looks like
[HttpPost]
public JsonResult Save_Document(DocumentModel doc)
{
// ... some code goes here
return (some json result);
}
When I check through browser there is post values passed by the view (the whole model is populated). In the controller I don't have ID of model (ID is always zero although the ID field is successfully posted through Ajax). Why the controller loose the ID model value?
DocumentModel is described as
public class DocumentModel
{
public int ID { get; set; } // does not work
public int id_folder { get; set; } // it works
public string document_number { get; set; } // it works
public System.DateTime document_date { get; set; } // it works
public string supplier_name { get; set; } // it works
public int id_employer { get; set; } // it works
public bool isChecked { get; set; } // this is dummy field. maybe it makes problem?
}
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.