Skip to content
Advertisement

How to use Action Link in Option tag to send parameters to the controller

I’m using a Select tag and I have foreach that adds the values to the list, but I have to call an Update Controller and pass it 2 parameters using ActionLink. I tried to do it this way but it doesn’t work. I wanted to know what I’m doing wrong?

<form action="Update " method="get" class="select-menu">
<select id="sectionId"
        name="sectionId"
        class="selectpicker"
        title="Section"
        data-width="100%"
        data-live-search="true"
        onchange="this.form.submit()">

       @foreach (var item in Model)
       {
           <option value="@item.Text" data-url="@Html.ActionLink(item.Text, "UpdateBoard", new { subSectionID = item.Value, subsectionName = item.Text })"></option>
       }
  </select>
</form>

The query should be something like this http://localhost:60082/Update?subSectionID=27&subsectionName=Something

Thank you!

Advertisement

Answer

Using the select tag inside the form in way described above will not work properly because of the form doesn’t have additional parameters for the route (subSectionID and subsectionName). As result, the Update action method will receiving subSectionID and subsectionName parameters as null.

Therefore, to make these parameters be set dynamically depend on a selection try the following:

<script type="text/javascript">

    $('#sectionId').change(function () {
        var url = $(this).val();
        if (url != null && url != '') {
            window.location.href = url;
        }
    })

</script>

<select id="sectionId"
        name="sectionId"
        class="selectpicker"
        title="Section"
        data-width="100%"
        data-live-search="true">

    @foreach (var item in Model)
    {
        <option value="@Url.Action("SetLanguage", new { subSectionID = item.Value, subsectionName = item.Text })">@item.Text</option>
    }
</select>

Inside the foreach use Url.Action helper instead of the Html.ActionLink. The Url.Action helper generates a fully qualified URL to an action method by using the specified action name and route values.

But the Html.ActionLink returns an anchor element for the specified link text, action and this may cause additional problems when will be passed to the server side.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement