may
may

Reputation: 33

@Html.DropDownListFor onchange is not calling the mentioned Action method

I am trying to call a controller method "GetTasksList" onchange of dropdown value in view. However onchange of dropdown, the "Edit" method of Controller is being called and submitting the form to database. This is undesirable because I am trying to fetch a list of tasks from the database based on the dropdownvalue.

enter image description here

View

 @Html.DropDownListFor(x => x.AuditDecision, (SelectList)ViewBag.ListofAuditDecision, "Please select", new { @class = "form-control input-10", id = "AuditStatus", onchange = "testing();", @style = "width: 300px;" })

<script>
  function testing() {
        alert("in testing");
        document.forms[0].action = 'GetAuditTasksList';
       // window.location.href = 'GetAuditTasksList';
        document.forms[0].submit();
    }
</script>

The control goes to below method

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Audit audit)
        {
 //submitting to database
}

instead of

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetAuditTasksList(Audit audit)
        {
}

Upvotes: 1

Views: 236

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11110

You should use a helper method to generate the correct action uri for the form. This way you can explicitly pass any required parameters and are protected from any future changes to your routing rules. eg;

    document.forms[0].action = '@Url.Action("GetAuditTasksList", ... )';

Upvotes: 1

Related Questions