简体   繁体   中英

When making an ajax request, how can I use a jquery variable in the url parameter that uses c#?

Here is the code that I have:

var selectedFacility = $("#Facility").val();

$.ajax({
        type: "Post",
        url: "@Url.Action("GetLocations", "Item", new { Facility = "selectedFacility goes here"})",
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                $('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
            }
        }
    });

Controller action:

public JsonResult GetLocations(string facility) {
        var Locations = new List<SelectListItem>{};
        Locations.AddRange(db.Locations.Where(l => l.Facility == "LAT").ToList().Select(l => new SelectListItem {
            Text = l.Name,
            Value = l.ID.ToString()
        }));
        return Json(Locations, JsonRequestBehavior.AllowGet);
    }

This is the line that I need to use the variable on:

new { Facility = "selectedFacility goes here"})",

I might be missing something obvious, but I need to use the selectedFacility jquery variable in the Url.Action() parameters. Is there a way that this can be done?

I think you can't use $("#Facility").val(); parameter in the Url.Action() method.

You are using http POST I think you can try to set the ajax data object to be the parameter.

var selectedFacility = $("#Facility").val();

$.ajax({
        type: "Post",
        url: '@Url.Action("GetLocations", "Item")',
        data: { Facility: selectedFacility },
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                $('#Location').append('<option value="' + data[i].Value + '">' + data[i].Text + '</option > ');
            }
        }
    });

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