提出Ajax请求时,如何在使用c#的url参数中使用jquery变量?

sjohn285

这是我的代码:

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 > ');
            }
        }
    });

控制器动作:

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);
    }

这是我需要在以下位置使用变量的行:

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

我可能缺少明显的东西,但是我需要selectedFacility在Url.Action()参数中使用jquery变量。有没有办法可以做到这一点?

D-Shih

我认为您不能$("#Facility").val();Url.Action()方法中使用参数

您正在使用http,POST我想您可以尝试将ajax数据对象设置为参数。

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 > ');
            }
        }
    });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章