MVC/JSON Cascading Dropdown List Displays [object Object]

asp.net-mvc-5 c# entity-framework-6 jquery json

Question

Greetings from a relative newbie.

I'm attempting to populate a dropdown list (Bill-To Address) based on the selected value in another dropdown list (Agency). The dependent dropdown list displays [object Object] when a value is selected in the first dropdown list. I'll need the ID from the second dropdown list to update a database record down the road.

I believe I'm missing something really basic/stupid here, but I've all but given up. I've searched for similar issues here but haven't yet found anything that resolves my issue.

Many, many thanks in advance!

Here are the relevant code snippets:

CreatePurchaseOrderViewModel.cs

// Agency dropdown list
[Required(ErrorMessage = "An agency must be selected.")]
public int AgencyID { get; set; }
public List<SelectListItem> AgencyList { get; set; }

// Agency bill-to address dropdown list
[Required(ErrorMessage = "A bill-to address must be selected.")]
public int BillToAddressID { get; set; }
public List<SelectListItem> BillToAddressList { get; set; }

PurchaseOrderService.cs

// Query vPurchaseOrderAddresses view to fetch
// a bill-to address for a given Id
public List<SelectListItem> GetBillToAddressByAgency(int Id)
{
    using (MyEntities db = new MyEntities())
    {
        var billtoAddressQuery = db.vPurchaseOrderAddresses.ToList()
            .Where(b => b.PartyID == Id)
            .Where(b => b.PCMPT == 2) // (2) = bill-to address
            .Select(b => new SelectListItem
            {
                Value = b.PartyID.ToString(),
                Text = b.Address
            });

        // Sort list ascending
        billtoAddressQuery = billtoAddressQuery.OrderBy(d => d.Text);

        return billtoAddressQuery.ToList();
    }
}

PurchaseOrderController.cs

[HttpPost]
public ActionResult GetBillToAddressByAgency(string selectedValue)
{
    // Create instance of PurchaseOrderService class
    PurchaseOrderService PO = new PurchaseOrderService();

    // Create a list to hold bill-to addresses from database
    List<SelectListItem> BillToAddressList = new List<SelectListItem>();

    // Populate bill-to address dropdown list by calling
    // the GetBillToAddressByAgency method of the PurchaseOrderService class.
    int i;
    if (Int32.TryParse(selectedValue, out i))
    {
        BillToAddressList = PO.GetBillToAddressByAgency(Convert.ToInt32(selectedValue));
    }

    return Json(new { billtoAddressList = BillToAddressList });

}

And, finally, the view: Create.cshtml

@*-- Agency dropdown list --*@
<div class="form-group">
    <label class="control-label col-md-2" for="AgencyID">Agency *</label>
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.AgencyID, Model.AgencyList, "-- Select Agency --")
        @Html.ValidationMessageFor(model => model.AgencyID)   
    </div>
</div>

<div class="form-group">
    <label class="control-label col-md-2" for="BillToAddressID">Bill-To Address *</label>
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.BillToAddressID, Model.BillToAddressList, "-- Select Bill-To Address --")
        @Html.ValidationMessageFor(model => model.BillToAddressID)
    </div>
</div>

<script type="text/javascript">
    $("#AgencyID").change(function () {
        var selectedValue = $(this).val();
        $.ajax({
            url: '@Url.Action("GetBillToAddressByAgency", "PurchaseOrder")',
            type: 'POST',
            data: { "selectedValue": selectedValue },
            dataType: 'json',
            success: function (response) {
                var items = "";
                $.each(response.billtoAddressList, function (i, item) {
                    items += "<option value=\"" + item + "\">" + item + "</option>";
                });
                $("#BillToAddressID").html(items);
            },
            error: function (error) {
            }
        });
    });
</script>
1
0
4/29/2014 5:57:24 PM

Accepted Answer

Replace this line items += "<option value=\"" + item + "\">" + item + "</option>";

By items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";

Regarding your code. As you can retrieve object which is good but you need to access to properties. I hope it will help you.

0
4/29/2014 6:37:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow