user788448
user788448

Reputation: 797

Pass Dropdown Selected Value as Action Method

I have dropdown options programs2019, programs2020 and when user selects programs2019 then it will call action method programs2019 in the controller. I tried to use jquery and pass selectedvalue to @Url.Action() without luck. I read a post that says "@Url.Action is server-side code, which is executed before any of the JavaScript code is executed. So you cannot reference JS variables in that @Url.Action() call.". How do I pass selectedvalue to call action then? My code as below:

 <span id="Label1">Select a program year</span> &nbsp;


        @Html.DropDownList("year", new List<SelectListItem>
{
new SelectListItem { Text = "2019", Value = "Programs2019"},
new SelectListItem { Text = "2020", Value = "Programs2020"}

}, "Select a year", htmlAttributes: new { style = "width: 300px;" })

and jquery:

<script  type="text/javascript">
$(document).ready(function () {

  $("#year").change(function () {
     var SelectedYr = $('#year').val();
    $.ajax({
        type: 'POST',
        url: '@Url.Action(SelectedYr)',
        dataType: 'json',
        data: { year: SelectedYr },
        success: function (result) {
        }

    });
});
});

controller:

 public ActionResult Programs2019()
    {
      ...
    }
   public ActionResult Programs2020()
    {
      ...
    }

Upvotes: 1

Views: 1547

Answers (1)

coposaja
coposaja

Reputation: 61

I think there are several solutions due to this problem.

Here are the two easiest ways:

You can use a raw string on ajax instead of @Url.Action then use some tricky javascript string concat on it.

$.ajax({
    type: 'POST',
    url: `/YourControllerName/Programs${SelectedYr}`,
    success: function (result) {}
});

Or you can do it this way

Merge the Actions on your Controller and use the selected year to separate the functionality

Controller

public ActionResult ProgramSelect(int year)
{
    if(year == 2019) {...}
    ...
}

Ajax

$.ajax({
    type: 'POST',
    url: '@Url.Action("ProgramSelect", "YourControllerName")',
    data: { year: SelectedYr}
    success: function (result) {}
});

Upvotes: 3

Related Questions