Call an action from a Html.Dropdown onchange event in ASP.Net MVC 5

I'm trying to call the action in the controller when the dropdown selected item changes. Here is the code I am using but it is not working.

 @Html.DropDownList("UserID", null, new { @onchange = "location.href='@Url.Action("Action", "Controller")'" })

What is the correct syntax? I tried to call a javascript function and it works.

@Html.DropDownList("UserID", null, new { @onchange = "leaveChange(this);" })

leaveChange(control) is my javascript function.

However, I am unable to invoke the action of the controller. Also, How do I then pass the value of the selected item to the action?

Upvotes: 1

Views: 26988

Answers (5)

Hien Nguyen
Hien Nguyen

Reputation: 18975

If you want to pass parameters to action you can use

@Html.DropDownList("UserID", null, new { onchange = "location.href='@Url.Action("Action", "Controller", 

    new {name = "Test param", category = "Test1"})'" })

Upvotes: 0

Aitezaz Bilal
Aitezaz Bilal

Reputation: 13

This code worked for me:

onchange = "location.href='" + @Url.Action("AdmissionRequirement", "Profile") + "'"

Upvotes: 0

Pallavi
Pallavi

Reputation: 36

Try removing @ before onchange

 @Html.DropDownList("UserID", null, new { onchange = "location.href='@Url.Action("Action", "Controller")'" })

Upvotes: 1

Here is what I did

 @Html.DropDownList("UserID", null,new {@id = "leve" })

Jquery code as below:

<script type="text/javascript">

                $('#leve').change(function () {
                    var url = "/UserRoles/TellMeDate";
                    var name = $('#leve').val();
                    $.get(url, { parameter: name }, function (data) {
                        alert(data);
                    });


                })

            });         




        </script>

Controller:

public string TellMeDate(string parameter)
    {


            return DateTime.Today.ToString() +"-->>>"+ parameter + "!!!!";


    }

Upvotes: 0

Shyju
Shyju

Reputation: 218732

You cannot call a C# method inside the htmlAttributes object where it expects a key value pair. Instead you could execute the Url.Action method and set the result(the url) on a parent element's data attribute and read from that in your javascript code

<div data-submit-url="@Url.Action("ApplyVacation","Jobs")">
    @Html.DropDownList("UserID",)
</div>

and in the change event, read it

$(document).ready(function ()
{
    $("#UserID").change(function ()
    {
        var $this = $(this);
        var url = $this.parent().data("submit-url") + "?userId=" + $this.val();
        window.location.href = url;
    });

});

When user make a selection on the SELECT, this code will navigate to the /Jobs/ApplyVacation url with querystring key userId and the selected option value as the value of that. Update the names as needed based on your code.

Upvotes: 4

Related Questions