Html.ActionLink with id value from a dropdownlist

馋奶兔 提交于 2019-12-22 05:54:29

问题


I've got a dropdownlist: <%= Html.DropDownList("ddlNames", new SelectList(Model.NameList, "ID", "Name"))%>

I've got an ActionLink: <%: Html.ActionLink("edit", "Edit", "Members", new { area = "MembersArea", id = XXX }, null)%>

I want the value of the dropdownlist in the XXX. So I want to use values from controls on a view in the ActionLink. Is that possible in a simple manner?

thanks,

Filip


回答1:


You can't do this because the html helpers execute at the server side while the dropdown value can change at the client side. The only way to achieve it is to use javascript. You could register for the onchange event of the dropdown and modify the value of the href of the anchor:

$(function() {
    $('#ddlNames').change(function() {
        var value = this.value; // get the selected value
        // TODO: modify the value of the anchor
    });
});

This is probably not the best solution because the routes are configured on the server side and in order to modify the value of the link you need to do some string manipulation on the client side.

As an alternative you could use a form and a submit button instead of an anchor. This way the selected value of the dropdown will be automatically sent to the server and you don't need any javascript:

<% using (Html.BeginForm("Edit", "Members", new { area = "MembersArea" })) { %>
    <%= Html.DropDownListFor(x => x.SelectedName, 
        new SelectList(Model.NameList, "ID", "Name"))%>
    <input type="submit" value="Edit" />
<% } %>



回答2:


Instead of modifying the value of the anchor every time a relevant dropdown is changed, just modify it once, on click.

Example using Razor:

@Html.DropDownList("DropDownFirstNames", new SelectList(Model.FirstNames, "ID", "Name"))
@Html.DropDownList("DropDownLastNames", new SelectList(Model.LastNames, "ID", "Name"))
@Html.ActionLink("Submit name", "ActionName", "ControllerName", null, new { @id = "SubmitName" })

<script type="text/javascript">
    $('#SubmitName').click(function () {
        var first = $('#DropDownFirstNames').val(); 
        var last = $('#DropDownLastNames').val();
        var path = '@Url.Content("~/ControllerName/ActionName")' + "?firstId=" + first + "+&lastId=" + last
        $(this).attr("href", path);
    });
</script>


来源:https://stackoverflow.com/questions/4113314/html-actionlink-with-id-value-from-a-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!