Monday, May 2, 2011

Passing Selected HTML.Dropdownlist through actionlink in MVC

I spent a bit of time today figuring out how to pass a selected value from an html dropdown list into an MVC actionlink so thought I would write a post on my findings.

OK, I have a category list on my page as follows:

<%:Html.DropDownList("Categories") %>

...and an actionlink link as follows:

<%: Html.ActionLink("Edit", "MaintainCategory", "CMS", new { ID = 0 }, new { id = "editlink" })%>

...I want the ID passed to be the value selected in the dropdown box.

The easiest way I found was to add the above JQuery / Javascript to the page:

<script type="text/javascript">

$(function () {
$('#Categories').change(function () {
var value = this.value; // get the selected value
//modify the href link
value = '/CMS/MaintainCategory/' + value;
$('#editlink').attr('href', value);

});
});