1

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....

In controller,

        var datacontext = new ServicesDataContext();
        var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
        var qw = (from m in datacontext.Mapings
                  where id == m.CustomerServiceMappingID
                  select m.CustomerID).First();
        ViewData["CustomerID"] = qw;
        int b = Convert.ToInt32(serviceToUpdate.ServiceID);
        var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
        ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);

In view:

    @Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)

serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...

nishanth yeddula
  • 77
  • 1
  • 3
  • 11

2 Answers2

0

I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.

Here is my question:

DropDownListFor Not Displaying/Persisting Null for First Choice in List

You shouldn't have to use view data explicitly either like you are doing.

Community
  • 1
  • 1
Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141
0

Code in Controller:

 ViewBag.Services = new SelectList(a, "ServiceId", "@Servicename");
  • ServiceId is the property representing the key-value for the item displayed in the dropdown list
  • @Servicename stands for the property representing the text you want to display for the item in the dropdownlist)

Code in View:

 @using(@BeginForm){
     SelectList services = Viewbag.Services;
     @Html.DropDownListFor(model => model.ServiceID, services)
 }
Tobias
  • 2,945
  • 5
  • 41
  • 59