I am trying to trigger an action method for onchange event for dropdownlist, how can I do this without using jquery onchange.

@Html.DropDownList("Sortby", 
                   new SelectListItem[] 
                   { 
                       new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
                       new SelectListItem() { Text = "Oldest to Newest", Value = "1" }})

Thanks


Solution 1:

If you don't want jquery then you can do it with javascript :-

@Html.DropDownList("Sortby", new SelectListItem[] 
{ 
     new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, 
     new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
     new { @onchange="callChangefunc(this.value)" 
});

<script>
    function callChangefunc(val){
        window.location.href = "/Controller/ActionMethod?value=" + val;
    }
</script>

Solution 2:

You can do this

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
  { 

       Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
       {
           onchange = @"form.submit();"
       }
})

Solution 3:

You can try this if you are passing a value to the action method.

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

Remove the query string in case of no parameter passing.

Solution 4:

try this :

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem() 
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

Solution 5:

first you need to give your dropdown onchange event;

@Html.DropDownList("ddl_reportId", new SelectList(ViewBag.ddl_reportName, "ddl_reportId", "ddl_reportName"), "Raporu seçin", new { @class = "form-control", @onchange = "getVal()" })

then in script section you have to call it like this.

function getVal() {
    var selectedVal = document.getElementById("ddl_reportId").value;
    console.log(selectedVal)};