I have a dropdownlist that uses an ajax call to post back to a JsonResult and populate a table element. When a value from the dropdown list returns no records, the javascript function returns an alert but when there are records returned, it doesn't go through the function. Here is my Dropdown list:
@Html.DropDownListFor(model => model.SelectedFiscalYear, Model.FiscalYears, new { onchange = "PopulateTransactions();" })
Here is my PopulateTransactions function:
function PopulateTransactions() {
alert("OK");
var success = function (results) {
var tbl = $("#tblTransactions");
tbl.empty();
alert(results.length);
for (var i = 0; i < results.length; i++) {
tbl.append("<tr><td>" + "Hello" + "</td><td>" + "World" + "</td></tr>");
}
};
$.ajax({
url: '@Url.Action("GetTransactions", "ProjectProjet")',
type: "POST",
data: {
id: $("#ActivityId").val(),
year: $("#SelectedFiscalYear").val()
},
dataType: "json",
success: success
});
}
And here is my JsonResult:
public JsonResult GetTransactions(int id, int year)
{
List<Transaction> data;
data = new Transaction().GetTransactionsByActivityFiscalYear(id, year);
return Json(data.ToArray());
}
Which returns entities from my database:
public List<Transaction> GetTransactionsByActivityFiscalYear(int id, int year)
{
using (MyEntities ctx = new MyEntities())
{
var query = ctx.Transactions.Where(a => a.ActivityId == id && a.ValueDate.Year == year).ToList();
return query;
}
}
As you can see from my function, the alert("OK") always displays but if there are results, my table does not get populated and I do not get the alert(results.length). If there are no results, then I get both alerts. My table gets populated on first load by my Controller but should be populated by the Javascript onchange event every time I change the dropdown list value. Here is my Html table:
<table id="tblTransactions">
@foreach (var tran in Model.TransactionsByFiscalYear)
{
<tr>
<td>
tran.ValueDate
</td>
<td>
tran.Value
</td>
</tr>
}
</table>
Can anyone see what I'm doing wrong? Thanks