如何获取下拉列表值并通过ActionLink传递给控制器​​?

时间:2018-08-27 21:03:12

标签: c# asp.net asp.net-mvc drop-down-menu

我需要使用Actionlink将下拉列表的值发送到控制器。

我正在使用以下代码:

发送列表以从控制器查看:

ViewBag.Frecuencies = new SelectList(db.Frecuencies, "FrecuencyID", "Description");

在“视图”中显示列表:

 @Html.DropDownList("Description", (IEnumerable<SelectListItem>) ViewBag.Frecuencies,new { name="Frecuency"})

,我想使用ActionLink作为参数从下拉列表中发送值:

@ActionLink("ActionName","Controller",new {**ParameterName=DropdownValue**})

有帮助吗?

2 个答案:

答案 0 :(得分:0)

我认为如果不使用JavaScript,您将无法做到这一点。您必须从列表中获取选定的值,然后将其添加到<a>生成的@Html.ActionLink()标记中。

首先,我将为这些Html帮助方法添加一些ID。

@Html.DropDownList("Description", (IEnumerable<SelectListItem>)ViewBag.Frecuencies, new { name = "Frecuency", id = "Frecuency-id" })

@Html.ActionLink("ActionName", "Controller", new { paramName="", id="action-link-id"})

然后您继续使用JavaScript。使用jQuery的方法如下:

var selectedValue = $("#Frecuency-id").val();

$("#action-link-id").attr("paramName", selectedValue);

当然,每次选择的值更改时,您仍然必须执行此代码。

var valueList = $("#Frecuency-id");

    valueList.on("change", function () {
        var selectedValue = $("#Frecuency-id").val();

        $("#action-link-id").attr("paramName", selectedValue);
    });

代码应该看起来像我上面描述的那样。

答案 1 :(得分:0)

假设您具有以下设置:

@Html.DropDownList("Description", (IEnumerable<SelectListItem>)ViewBag.Frequencies, new { id = "Frequency" })

@Html.ActionLink("Link Text", "ActionName", "ControllerName", null, new { id = "Link" })

然后您可以使用查询字符串来操纵链接的href属性:

$('#Frequency').change(function () {
    var ddlValue = $(this).val();
    var url = $('#Link').attr('href');

    $('#Link').attr('href', url + '?ParameterName=' + ddlValue);
});

如果链接已经具有这样的参数值:

@Html.ActionLink("Link Text", "ActionName", "ControllerName", new { ParameterName = "OtherValue" }, new { id = "Link" })

然后您可以按如下所示替换参数值:

$('#Frequency').change(function () {
    var ddlValue = $(this).val();

    $('#Link').attr('href', function () {
        return this.href.replace("OtherValue", ddlValue);
    });
});

请注意,ActionLink提供的参数值是在服务器端处理的,它会创建具有href属性的锚标记,其中包含带有控制器名称,操作名称和查询字符串参数的URL,如下例所示:

<a id="Link" href="/ControllerName/ActionName?ParameterName=[DDLValue]">Link Text</a>
相关问题