0

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

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
devguy
  • 37
  • 1
  • 9
  • 1
    Are you getting any console errors? You should encode your passed data with `data: JSON.stringify: ({ id: $("#ActivityId").val(), year: $("#SelectedFiscalYear").val()}),`. I would then suggest adding an `error:` setting after your success such as `error: function(jqXHR, textStatus, errorThrown) {console.log(textStatus, errorThrown); }` to see whats happening. – Steven B. Sep 20 '16 at 13:49
  • is GetTransactions method get called ?. Try this write the success function after the ajax function. – Balan Sep 20 '16 at 19:58
  • Yes, the GetTransactions does get called. I've also moved the success function below and even added it to the success call but either one of those worked. @Balan – devguy Sep 21 '16 at 13:49
  • @lamelemon I tried the JSON.stringify, although I removed the colon right after it because it was causing an error, but that didn't work. I added the error function and changed the Console.log to an alert and all I get is "error". If I'm returning a List of Entities from my GetTransactions method, could there be something wrong with returning data.ToArray()? I've also tried: return new JsonResult() { Data = data } – devguy Sep 21 '16 at 14:00
  • @devguy Yeah I didn't mean to type that colon. I guess the next thing is too see if you're actually hitting the controller. Start debugging and put a breakpoint on the controller to see if your ajax method is hitting it. If you are not hitting it I would put `[HttpPost]` directly above your controller's `GetTransactions()` function. There probably is an issue with that how you convert your data to JSON. I suggest using the builtin JavascriptSerializer directly on your list something like `return new JavaScriptSerializer().Serialize(data);` – Steven B. Sep 21 '16 at 14:31
  • @lamelemon Yeah...no problem hitting the controller. I changed it to use the Javascript Serializer and changed my method to return a string and I get this error: "Exception has been thrown by the target of an invocation". When I look at the InnerException, I get "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.". So I wrapped my call in a using statement to populate data and I get this error: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Transaction_545BED9548 etc... – devguy Sep 21 '16 at 17:47
  • I think I'm close...I use this type of code to populate other fields on my page but those are individual items. It only fails when I'm return a list of Entities. – devguy Sep 21 '16 at 17:47
  • @devguy Probably something to do with lazy loading. There are a few questions here on SO that may help you with the ObjectContext issue such as [this](http://stackoverflow.com/questions/18398356/how-to-solve-the-error-the-objectcontext-instance-has-been-disposed-and-can-no-l) or [this](http://stackoverflow.com/questions/27581352/the-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-opera) . Also, it may be worth adding `contentType: "application/json; charset=utf-8",` in your ajax call. – Steven B. Sep 21 '16 at 19:53

1 Answers1

0

@lamelemon I got it. I created a POCO class for my Transactions and take my entity and populate this class. When I return this new class it works fine. I guess Entity Framework has a problem serializing. Thanks to everyone for your help.

devguy
  • 37
  • 1
  • 9