" />
开发者

Html.ActionLink with id value from a dropdownlist

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 drop开发者_如何学Godownlist 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


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" />
<% } %>


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜