I have an object Modem
with the property Protocol
which is bound to a DropDownListFor
. The value of Modem in the DropDownList isn't selected.
public class Modem {
public Protocol Protocol { get; set; }
}
public class Protocol {
public string Name { get; set; }
public string Value { get; set; }
}
My Controller code
var modem = new Modem{ Protocol = new Protocol { Name = "UDP", Value = "The udp protocol" } };
var protocols = new List<Protocol>{ new Protocol { Name = "TCP", Value = "The tcp protocol" }, new Protocol { Name = "UDP", Value = "The udp protocol" } };
ViewBag.Protocols = protocols.Select(p => new SelectListItem{ Value = p.Name, Text = p.Value });
return View(modem);
My View code
@Html.DropDownListFor(modem => modem.Protocol, (IEnumerable<SelectListItem>) ViewBag.Protocols)
If I manually set the selected protocol that doesn't work. So can I implement Equals
like this (already tried doing this with Protocol
, but it didn't work...)
public bool Equals(object obj){
if(obj == null){
return false;
}
var protocol = obj as Protocol;
return protocol != null && protocol.Name == Name;
}
Update : I tried using
@Html.DropDownListFor(modem => modem.Protocol, new SelectList(ViewBag.Protocols, "Name", "Value", Model.Protocol))
But didn't work too :(.
Update 2 : Using reflector, I have found this line :
HashSet<string> set = new HashSet<string>(from value in enumerable.Cast<object>() select Convert.ToString(value, CultureInfo.CurrentCulture), StringComparer.OrdinalIgnoreCase);
So DropDownListFor uses the ToString method to do the set of the default value. With this ToString method, I could do what I wanted :
public override string ToString()
{
return Name;
}