Tuesday, January 6, 2015

Bind the dropdown list & select the required value in dropdownlist in ASP.Net MVC 4 Webgrid

I was struggling to select the value in dropdown. The value comes from database.

I dont think there is a straight way to achieve this unless we do a work around. (please update me if there is!!!)

The work around I did was...

in each collection which we use to bind dropdownlist use "selected=True" for the required value.

i know it sounds crazy, but we dont have any other choice (atleast I dont know any at this time).


It will be a extra step we need to do in controller after we bind the collection to one of the properties of the model.


(I cannot paste my code here...I am sorry)

The steps will be

1. Get the collection of items of the dropdown  [Ex: List<SelectListItem> (City/State)]

2. Iterate through each record of the model  [foreach (Employee emp in Employees)]

3. Assign the collection to the property of the model [Ex: emp.Cities=listCities]

4. Set the Selected property to true to the required value [Ex:- emp.Cities[x].Selected=true]


This is how I found the solution to my requirement. happy coding



No comments:

Post a Comment