Monday 26 October 2015

MVC5 pass DroDownList Selected Item to controller using JavaScript Async



There are many methods where you can pass the selected Item in a Dropdownlist to a controller. Most common methods are Post requests to a controller where you pass the whole forms collection.

In this module , I need to view the Account report before I fill in the form data. So I cant use a HTTP Post here because the form data is not yet ready.

Following is a very simple way of accomplish this using Ajax and JS.


 
 function NavigateToReport() {
            var List = document.getElementById("AgencyId");
            var id = List.options[List.selectedIndex].value;

            var url = '@Url.Action("AgentAccount", "LocalAgencyAdditions", new { id = "__id__"})';
            window.location.href = url.replace('__id__', id);
        }

Just define a new Action Method in the controller.
 
 public async Task AgentAccount(int? id)
        {

            if (id != null)
                return RedirectToAction("AgentAccount", "Report", new { agentId = id, type = 2 });

            return RedirectToAction("Index");

        }

No comments:

Post a Comment