1

I am having a issue where my select dropdowns are working for some and not others. I have debugger in the code and breakpoints. When I select the first list which is Company it drops down with all the available Companies. That then populates all the Addresses for that Company. Some work fine and then others do not.

It hits the controller JsonAction on the breakpoint I get a Read on the count which works fine and then does not populate. I am getting a Object error in the Console window and it says first that there is a 500 error that it cannot find the action, but it does because it hits the breakpoint. Then the object error seems to be reading the entire page html Under Response Text of the Object.

My Controller:

    [HttpGet]
    public ActionResult PlaceQuote()
    {
        GeneralEntities generalEntities = new GeneralEntities();
        List<SelectListItem> Company = new List<SelectListItem>();
        Quotes casModel = new Quotes();
        List<CompanyNames> companies = generalEntities.CompanyNames.ToList();
        companies.ForEach(x =>
        {
            Company.Add(new SelectListItem { Text = x.CompanyName, Value = x.CompanyId.ToString() });
        });
        casModel.CompanyNames = Company;

        return View(casModel);
    }

My Dropdowns:

 <div class="form-group ">
     @Html.LabelFor(model => model.CompanyId, htmlAttributes: new { @class = "control-label" })
     @Html.DropDownListFor(model => Model.CompanyId, new SelectList(Model.CompanyNames, "Value", "Text"), "---Select Company---", new { @class = "form-control ", @id = "ddlCompany" })
     @Html.ValidationMessageFor(model => model.Address.Country, "", new { @class = "text-danger" })
 </div>

 <div class="form-group">
     @Html.LabelFor(model => model.AddressId, htmlAttributes: new { @class = "control-label " })
     @Html.DropDownListFor(model => Model.AddressId, new List<SelectListItem>(), "---Select Address---", new { @class = "form-control ", @id = "ddlAddress" })
     @Html.ValidationMessageFor(model => model.AddressId, "", new { @class = "text-danger" })
 </div>

My JavaScript:

    $(function () {
    $('#ddlCompany').change(function () {
        debugger;
        $.ajax({
            type: "post",
            url: "/Users/AddAddress",
            data: { companyId: $('#ddlCompany').val() },
            datatype: "json",
            traditional: true,
            error: function (_, err) {
                console.log(_, err)
            },
            success: function (data) {
                debugger;
                $('#ddlAddress')
                    .empty();
                $.each(data, function (index, value) {
                    $('#ddlAddress').append('<option value="' + value.AddressId + '">' + value.Line2 + '</option>');
                });
            }
        });
    });

    $('#ddlAddress').change(function () {
        debugger;
        $.ajax({
            type: "post",
            url: "/Users/AddUser",
            data: { userId: $('#ddlAddress').val() },
            datatype: "json",
            traditional: true,
            error: function (_, err) {
                console.log(_, err)
            },
            success: function (data) {

                $('#ddlUser')
                    .empty();
                $.each(data, function (index, value) {
                    $('#ddlUser').append('<option value="' + value.FirstName + '&nbsp;' + value.LastName + '">' + value.FirstName + '&nbsp;' + value.LastName + '</option>');
                });
            }
        });
    });
});

My JsonAction:

    public JsonResult AddAddress(string companyId)
    {
        int Id;
        Id = Convert.ToInt32(companyId);

        var address = (from a in db.Addresses where a.CompanyId == Id select a).ToList();
        return Json(address);

    }

I have checked my tables and there doesn't seem to be anything wrong with the data. The only difference in the records that do and do not populate, is that I added them through the website the ones that populate were added by Customers. The records that do not populate do not have users in the system, but my code checks for users in the next dropdown but I would think that the error would occur when selecting the user, Which is not working for any of them right now. When I remove the second part of the JavaScript to not select a user and just have user as a EditorFor, none of them work.

I am really confused on this and need some guidance.

UPDATE:

I thought I would mention that I have found that one of them that I added does work. I also Successfully removed the dropdown for users and the ones that populated before, still work. Which rules out errors with users and Customers I added.

Here is a screenshot of the Console window:

Console Window

UPDATE: Still trying to debug this.. Below is what Json is bringing back on a good selection vs a bad. The bad seems to be the whole html page instead of a json string..

Good: Good Response

Bad Response

UPDATE: Trying all angles.. I am going straight to the url with an Id. The ones that work produce a string. The ones that do not produce a 500 Error. In Elmah it is saying - A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Addresses_AA62E15399B3645C48D42185AF1DAE6F4765400DBB7E67EFA5202BAE2D5CA8CE'.

I have looked it up and did add:

    public JsonResult AddAddress(string companyId)
    {
        int Id;
        Id = Convert.ToInt32(companyId);
        db.Configuration.ProxyCreationEnabled = false;
        var address = (from a in db.Addresses where a.CompanyId == Id select a).ToList();
        return Json(address, JsonRequestBehavior.AllowGet);

    }

The db.Configuration.ProxyCreationEnabled = false; Seemed to cure the Issue. I am Unfamiliar as to why it was doing this on some and not all. Anyone that can explain that to me would be great...

Scott Purtan
  • 237
  • 1
  • 10
  • Tell us the exact error messages rather than alluding to them, please – ADyson Dec 10 '20 at 18:41
  • You are getting a 500 error. Following is doing similar for 415 : https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0#ialwaysrunresultfilter-and-iasyncalwaysrunresultfilter – jdweng Dec 10 '20 at 18:48
  • @ADyson it is a 500 error but it does not happen on all selections. – Scott Purtan Dec 10 '20 at 19:06
  • @jdweg So what you are saying is that it cannot find it, but it does.. It shows me the count it just doesn't populate the dropdown. Then says there is a 500 error that it cannot find the url. – Scott Purtan Dec 10 '20 at 19:07
  • 500 Internal Server Error is a generic error message informing you that the server crashed while processing the request. Beyond that, it's (intentionally) meaningless, and is of very little use for debugging. You need to check the error logs on the server to try and find the underlying exception message. Once you've got that, you stand a chance of identifying the root cause of the problem. – ADyson Dec 10 '20 at 19:33
  • You also said "I am getting a Object error in the Console window" ...so can you please tell us _exactly_ what that message is, too. – ADyson Dec 10 '20 at 19:34
  • @ADyson The Error is just "Error" in id being populated by the javascript where i have consol.log. Under that is Object. Under Object there are several things listed that branch in a tree form. I will see if I can post a screenshot. – Scott Purtan Dec 10 '20 at 19:50
  • I see. It's probably just the JS object representing the 500 error then. I thought you meant you had a JS script error. So you need to go back to looking for the error on the server. You might possibly get a clue if you inspect that responseText as well? It looks like a HTML document, so probably the asp.net error page - maybe it contains an actual error message within it? – ADyson Dec 10 '20 at 19:56
  • " A circular reference was detected ".... "Unfamiliar as to why it was doing this on some and not all"...probably because some of the records had foreign keys to other tables and others didn't? That's the best guess without seeing any actual data. And in EF, the relationships between tables are represented by properties in a class which point to the classes which represent other tables. So there's a danger you could have a situation where an object eventually has a property pointing back to itself...and you can't serialise that to JSON, because it's an infinite recursion. – ADyson Dec 10 '20 at 22:51
  • This is the reason why most people say it's good practice to use DTO / viewmodel classes to pass data back and forth between the client and server, and keep the EF data classes strictly within the boundaries of the application's data processing layer. – ADyson Dec 10 '20 at 22:52
  • More context here https://stackoverflow.com/questions/1153385/a-circular-reference-was-detected-while-serializing-an-object-of-type-subsonic (and in many other places, if you just paste "A circular reference was detected while serializing an object" into google) – ADyson Dec 10 '20 at 22:53
  • 1
    @ADyson I Agree and use them myself. However there are a few that I need to implement as the company I hired to do this used the model classes in some instead of creating view models. Only at my request did they start so I have some cleanup to do.. Thanks all for your responses. I have a good idea now why it may be happening. – Scott Purtan Dec 11 '20 at 01:26

0 Answers0