Link to home
Start Free TrialLog in
Avatar of hums
humsFlag for United States of America

asked on

Getting a selectd item back from a MVC dropdown list view ?

I have a drop down list that I populate in my MVC controller with the following code.

var allCustomers = _customerService.GetCustomersByCustomerRoleId(3, false);

             var customerList = new List<SelectListItem>();
             
             foreach (var cr in allCustomers)
             {
                 if (!cr.IsAdmin())
                 {
                     var item = new SelectListItem()
                     {

                         Text = cr.Email,
                         Value = cr.Id.ToString()
                     };
                     customerList.Add(item);
                 }
             }
             ViewData["CustomerID"] = customerList;

In the cshtml file the drop down list is populated with the following code.

     @Html.DropDownList("CustomerID")

Everything is working just fine.

My question is how do you return the selected value from the drop down list to the  controller?
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

why do u wanna return it to the controller?
if you use MVC, you should have some kind of service call from your client side (ajax maybe) passing relevant data to the service, via json format or xml or whatever.
Well you would do it with ajax:

$('#CustomerID').change(function(){

var th = $(this):
var itemval = th.children('option:selected').val();

$.ajax({
url: 'controller_url',
type: 'either post or get' // eg. : type:'post',
data: 'data='+itemval,
success: function(data){
// do something with server response here.
}
})

});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hums
hums
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial