Randy Minder
Randy Minder

Reputation: 48402

MVC 4 - Executing an action link based on the contents of a selected dropdown value

In one of my views I have a drop down list as follows:

<div id="CurrentExchange" style="position:absolute; right:150px; top:250px;">
    <h3>Select an Exchange</h3>
    <select>
        <option value="Bicycle" selected>Bicycle Exchange</option>
        <option value="Tennis">Tennis Exchange</option>
    </select>
</div>

Elsewhere in the same view I have an action link as follows:

@Html.ActionLink("click here", "Index", "BicycleSellerListing")

What I would like to do, and don't know how (I am very new to MVC and HTML) is something like this, in pseudo code:

if CurrentExchange = "Bicycle"
    @Html.ActionLink("click here", "Index", "BicycleSellerListing")
else if CurrentExchange = "Tennis"
    @Html.ActionLink("click here", "Index", "TennisSellerListing")
else if ...

Upvotes: 0

Views: 1777

Answers (1)

Steven V
Steven V

Reputation: 16595

You'll probably need to use a little Javascript to pull this off. On the link that you'll want the action to take place, you'll want something like:

<a href="javascript:void(0);" onclick="NavigatePage();">click here</a>

Granted there are a couple of ways to get the click event from the "click here" button using Javascript, but that's a slightly different discussion.

From there, somewhere on the page you'll some Javascript that will hold the NavigatePage function

<script type="text/javascript">
function NavigatePage() {
    var selectedValue = document.getElementById('CurrentExchange').value;
    if(selectedValue == "Bicycle")
        document.location = '@Url.Action("Index", "BicycleSellerListing")';
    else if(selectedValue == "Tennis")
        document.location = '@Url.Action("Index", "BicycleSellerListing")';
    else if // add as needed
}
</script>

You could also hard code the document.location values instead of using the UrlHelper if you wished. But it may give you flexibility in the future to leave it using the UrlHelper.

Upvotes: 1

Related Questions