简体   繁体   中英

Dropdown change not calling method asp.net mvc jquery

first off I have used this thread to get where I am now but am having difficulty with my situation. ASP.NET MVC 3 DropDownList selectedindexchanged

I wish to select a value from one dropdown list which will then reduce the available options on a dropdown below it.

Similar to the thread above, I am trying to use jQuery to accomplish this like so:

    $('#Park').change(function () {
        var queryLink = 'Url.Action("GetBuildings")';
        if ($(this).val() != '') {
            queryLink += '?parkID=' + $(this).index;
        }
        $.get(queryLink, function (data) {
            $b = $('#Building');
            $op = $('<option></option>');
            $b.empty();
            $.each(data, function (value) {
                $b.append($op.attr("value", value));
            });
        });
    });

and here is the GetBuildings function in the AvailabilityController:

public ActionResult GetBuildings(int parkID)
    {
        var buildQry = from b in systemDB.Buildings
                        where b.ParkID == parkID
                        orderby b.BuildingName
                        select b.BuildingName;
        string temp = "";
        foreach (string b in buildQry)
        {
            temp += b + ';';
        }
        temp = temp.Substring(0, temp.Length - 1);
        string[] buildings = temp.Split(';');

        return View(buildQry);
    }

However, when I change the value of the "Park" dropdown, nothing happens. No change to the URL, which due to the Url.Action("GetBuildings") I assumed would append "/GetBuildings?parkID=2" or something similar.

I'm not sure why it isn't at least doing something as I have made it as similar to the original thread as possible which worked correctly.

Thanks in advance!

For me this line is the issue:

var queryLink = 'Url.Action("GetBuildings")';

If you are doing that on the same view you can parse the asp tag by doing (note the @ ):

var queryLink = '@Url.Action("GetBuildings")';

But i don't recommend that approach, you get get away cleaner than that with a html5 data-attribute

EDIT: using data-attribute example. Add to the dropdown element an attribute like:

<select id="Park" data-action-url='@Url.Action("GetBuildings")'>

on your js you get the url:

var queryLink = $(this).attr('data-action-url');

You can also add the parameter to the url by using the $.get data parameter:

$.get(queryLink, {parkID : $(this).val()}, function (data) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM