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>
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top