根据DropDownList选择的值更改URL ID

时间:2017-02-13 14:41:18

标签: c# asp.net-mvc

我有一个DropDownList,它有一个Car models

@Html.DropDownList("Cars", (IEnumerable<SelectListItem>)ViewBag.Cars, "Select a Value", htmlAttributes: new { @class = "form-control" }) 我需要用户必须选择一个值,如果他选择一个特定值,将值的id发送到url作为参数的动作

<a href="@Url.Action("Edit", "Registration", new { id = selected value of the dropdownlist item })" class="text-white"> Modify Registration</a> <a href="@Url.Action("Delete", "Registration", new { id = selected value of the dropdownlist item })" class="text-white"> Cancel Registration</a>

1 个答案:

答案 0 :(得分:3)

您需要使用javascript来实现此目的。例如,您可以为锚点提供唯一的ID:

<a id="editRegistration" href="@Url.Action("Edit", "Registration", new { id = "initial value from the database" })" class="text-white">Modify Registration</a>

然后订阅下拉列表的更改事件并更新锚点的href:

<script>
    $('#Cars').change(function() {
        var url = "@Url.Action("Edit", "Registration", new { id = "#ID#" })";
        // replace the #ID# placeholder with the selected value
        var newHref = url.replace('#ID#', this.value);
        $('#editRegistration').attr('href', newHref);

        // do the same with the other anchor
    });
</script>