C# 如何获取dropdownlist值并通过ActionLink传递给控制器?
我需要使用Actionlink将下拉列表的值发送到我的控制器 我正在使用以下代码: 从控制器发送要查看的列表:C# 如何获取dropdownlist值并通过ActionLink传递给控制器?,c#,asp.net,asp.net-mvc,drop-down-menu,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="Frecue
ViewBag.Frecuencies = new SelectList(db.Frecuencies, "FrecuencyID", "Description");
@Html.DropDownList("Description", (IEnumerable<SelectListItem>) ViewBag.Frecuencies,new { name="Frecuency"})
在视图中显示列表:
ViewBag.Frecuencies = new SelectList(db.Frecuencies, "FrecuencyID", "Description");
@Html.DropDownList("Description", (IEnumerable<SelectListItem>) ViewBag.Frecuencies,new { name="Frecuency"})
有什么帮助吗?我认为如果不使用JavaScript,您无法做到这一点。您必须从列表中获取所选值,然后将其添加到
@Html.ActionLink()
生成的
标记中
首先,我将向那些Html
helper方法添加一些id
@Html.DropDownList("Description", (IEnumerable<SelectListItem>)ViewBag.Frecuencies, new { name = "Frecuency", id = "Frecuency-id" })
@Html.ActionLink("ActionName", "Controller", new { paramName="", id="action-link-id"})
当然,每次选择的值更改时,您仍然必须执行此代码
var valueList = $("#Frecuency-id");
valueList.on("change", function () {
var selectedValue = $("#Frecuency-id").val();
$("#action-link-id").attr("paramName", selectedValue);
});
代码看起来应该有点像我上面描述的。假设您有以下设置:
@Html.DropDownList("Description", (IEnumerable<SelectListItem>)ViewBag.Frequencies, new { id = "Frequency" })
@Html.ActionLink("Link Text", "ActionName", "ControllerName", null, new { id = "Link" })
如果链接已具有如下参数值:
@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>
首先,您应该使用模型,而不是ViewBag来将数据从控制器传递到视图,反之亦然。我认为如果不使用JavaScript,您无法做到这一点。您必须从列表中获取所选值,然后将其添加到@Html.ActionLink()
生成的
标记中。谢谢,最后,我使用了绑定模型
<a id="Link" href="/ControllerName/ActionName?ParameterName=[DDLValue]">Link Text</a>