ASP.Net MVC dropdown selected value while editing a record
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;
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...
However, I turned one more thing where in controller, I did something like this,
ViewData["ServiceID"] = new SelectList(a,"ServiceID","ServiceID");
Here, I get an error saying
'System.Int32' does not contain a property with the name 'ServiceID'.
What happens when you change
ViewData["ServiceID"] = new SelectList(a,"ServiceID","ServiceID");
to
ViewData["SelectListServiceID"] = new SelectList(a,"ServiceID","ServiceID");
and in your view:
@Html.DropDownListFor(model => model.ServiceID, ViewData["SelectListServiceID"] as SelectList)
I have seen this before and it has to do with automatic binding. You probably have a property named ServiceID in your model.
精彩评论