Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete with a foreign key using jQuery

I have an application dealing with Donations from Houses for a Church. I would like it so when a donation comes in to the Church, someone will type in a textbox the address but as there will be a lot of homes, I want an autocomplete box to make it easier.

Here are my models:

 public class Donation
{
    [Key]
    public int DonationId { get; set; }

    public string TypeOfDonation { get; set; }

    public decimal Amount { get; set; }

    [ForeignKey("Church")]
    public int ChurchId { get; set; }

    [ForeignKey("House")]
    public int HouseId{ get; set; }

    public virtual Church Church { get; set; }
    public virtual House House { get; set; }

}

public class House
{
    [Key]
    public int HouseNumber { get; set; }

    public string AddressLine1 { get; set; }

    public string AddressLine2 { get; set; }

    public string AddressLine3 { get; set; }

}

I think I am doing something wrong in my controller method:

public JsonResult GetAddress(string term)
    {
        var items = db.Houses
            .Where(x => x.AddressLine1.Contains(term))
            .Select(x => new { Label = x.HouseNumber, Value = x.AddressLine1 })
            .Take(10);

        return Json(items, JsonRequestBehavior.AllowGet);
    }

Or my jQuery:

 <div class="form-group">
        @Html.LabelFor(model => model.House.HouseNumber, "Address", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
           @Html.TextBoxFor(m => m.House.HouseNumber, new { id = "HouseNumber" })
           @Html.ValidationMessageFor(model => model.House.HouseNumber, "", new { @class = "text-danger" })
        </div>
    </div>

$('#Address').autocomplete({
source: function(request, response) {
    $.get('@Url.Action("GetAddress", "DonationsController")',
        { term: request.term },
        function(data) {
            response($.map(data, function (item) {
                return {
                    label: item.Label,
                    value: item.Value
                }
            }));
        });
},
minLength: 2
})

Can anyone point me in the right direction?

EDIT: Problem

like image 944
Chloe Finn Avatar asked Apr 27 '26 06:04

Chloe Finn


1 Answers

Your screenshot shows the problem.

When creating URLs in MVC, you should not include the word "Controller", even though the controller class is called DonationsController

Change it to

  $.get('@Url.Action("GetAddress", "Donations")',

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!