***I am trying to pass a list from controller to ajax in success. Its a post request from ajax. *** When I am trying it comes as [model model]
*This my controller
public JsonResult CreatePackage(string Package)
{
new ProductQueries().InsertTable("Packages", _DataBaseName, Package);
List<Packages> packages = new ProductQueries().GetPackageTable("Packages", _DataBaseName);
return Json(packages);
}
**This is my ajax please can someone let me know what I am doing wrong. Using after ages bit rusty on it any help is appreciated**
function CreatePackage() {
var Package = $('#Package').val();
$.ajax({
type: 'POST',
dataType: 'JSON',
url: '@Url.Action("CreatePackage", "Product")',
data: { Package },
success:
function (data) {
console.log(data);
debugger;
$.each(data, function (key, item) {
$("DropDownList").append('< label class="dropdown-option" ><input type="checkbox" name = "dropdown-group" value = "' + key+ '" />' + item+ '< /label>');
});
}
});
}
**This is my model**
public class Packages
{
public int Id { get; set; }
public string Package { get; set; }
}
You're returning a list of objects:
List<Packages> packages = //...
return Json(packages);
Then looping over that list:
$.each(data, function (key, item) {
And trying to render an object as a string:
'<label class="dropdown-option"><input type="checkbox" name="dropdown-group" value="' + key + '" />' + item + '</label>'
But an object isn't a string. It's an object. What string value would you expect it to render as and why?
Your object has two properties:
public int Id { get; set; }
public string Package { get; set; }
Are you intending to use the Package
property in your output? If so then use that property:
'<label class="dropdown-option"><input type="checkbox" name="dropdown-group" value="' + key + '" />' + item.package + '</label>'
(Note: It may be item.package
or item.Package
depending on your JSON serialization settings.)
It also seems likely that you probably want to use item.id
instead of key
, since key
is an otherwise meaningless array index:
'<label class="dropdown-option"><input type="checkbox" name="dropdown-group" value="' + item.id + '" />' + item.package + '</label>'
(Note: It may be item.id
or item.Id
depending on your JSON serialization settings.)
Basically, the system has no way of knowing how you want your object to be represented as a string. You have to specify that when outputting it.