Using select, option value inside the actionlink

1.2k Views Asked by At
if (@ViewBag.Title == "Title")
{

@ViewBag.Title
<div class="btnNEW" hidden id="fqXLS">
<select id = "fqcXLS">
<option id ="fqcXLSa">A</option>
<option id ="fqcXLSb">B</option>
<option id ="fqcXLSc">C</option>
<option id ="fqcXLSd">D</option>
</select>

@Html.ActionLink("Export To Excel", "ExportToExcel", "EEC", new { option = ??? }, new { @class = "cancel" })
</div>
}

I was able to make it work just by doing new{option="A"} but this will only send "A"

How can I use the selected value?

1

There are 1 best solutions below

18
haldo On BEST ANSWER

The ActionLink is created when the page is first rendered. It is not updated when the user selects from the dropdownlist (it will have the same initial value). Therefore, you will need to update the anchor href value using javascript or jquery.

There are many ways to achieve this, below is an unobtrusive way:

1) Give the ActionLink an ID:

@Html.ActionLink("Export To Excel", 
                 "ExportToExcel", 
                 "EEC", 
                  null, 
                  new { @id = "lnkCancel", @class = "cancel" })

2) Add event listener for the onchange event of the dropdown list (this should be called once the document is ready/loaded):

// get the dropdownlist
var ddl = document.getElementById('fqcXLS');

// add event listener for 'onchange'
ddl.addEventListener('change', function () {
    var url = '@Url.Action("ExportToExcel", "EEC")';           // base url
    var link = document.getElementById('lnkCancel');           // get link to update 
    var selectedValue = ddl.options[ddl.selectedIndex].value;  // get selected value
    link.href = url + '?option=' + selectedValue;              // update link href
}); 

This will update the anchor href attribute when the select list is changed.

var ddl = document.getElementById('mySelect');

ddl.addEventListener('change', function () {

  var url = 'somesite/myaction';           // base url
  var link = document.getElementById('lnkCancel');           // get link to update 
  var selectedValue = ddl.options[ddl.selectedIndex].value;  // get selected value
  link.href = url + '?option=' + selectedValue;              // update link href
  
  link.innerText = link.href;  // dont include this, this just shows the url text
});
<select id="mySelect" >
    <option value="A" selected>A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
    <option value="E">E</option>
 </select>
  
  <a href="somesite/myaction" id="lnkCancel" >Select item in dropdown</a>