Html.ActionLink with id value from a dropdownlist

Filip picture Filip · Nov 6, 2010 · Viewed 17.7k times · Source

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

Answer

Darin Dimitrov picture Darin Dimitrov · Nov 7, 2010

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