Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 850
Filip Avatar asked Nov 06 '10 13:11

Filip


2 Answers

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" />
<% } %>
like image 99
Darin Dimitrov Avatar answered Sep 24 '22 19:09

Darin Dimitrov


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>
like image 31
Carson Herrick Avatar answered Sep 21 '22 19:09

Carson Herrick