C# 使用非基本体对象为DropDownListFor实现Equals
我有一个对象C# 使用非基本体对象为DropDownListFor实现Equals,c#,asp.net,asp.net-mvc-4,razor,dropdownlistfor,C#,Asp.net,Asp.net Mvc 4,Razor,Dropdownlistfor,我有一个对象Modem,其属性为Protocol,它绑定到DropDownListFor。未选择DropDownList中调制解调器的值 public class Modem { public Protocol Protocol { get; set; } } public class Protocol { public string Name { get; set; } public string Value { get; set; } } 我的控制器代码 var
Modem
,其属性为Protocol
,它绑定到DropDownListFor
。未选择DropDownList中调制解调器的值
public class Modem {
public Protocol Protocol { get; set; }
}
public class Protocol {
public string Name { get; set; }
public string Value { get; set; }
}
我的控制器代码
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);
更新:
我试着用
@Html.DropDownListFor(modem => modem.Protocol, new SelectList(ViewBag.Protocols, "Name", "Value", Model.Protocol))
但也不起作用:(
更新2:
使用reflector,我发现了这条线:
HashSet<string> set = new HashSet<string>(from value in enumerable.Cast<object>() select Convert.ToString(value, CultureInfo.CurrentCulture), StringComparer.OrdinalIgnoreCase);
您根本不需要实现
Equals
-只需在POST处理操作中执行从SelectListItem.Value
到协议
类的反向映射。我不明白。显示表单时,我希望DropDownList具有模型。协议具有默认值。
@Html.DropDownListFor(modem => modem.Protocol, new SelectList(ViewBag.Protocols, "Name", "Value", Model.Protocol))
HashSet<string> set = new HashSet<string>(from value in enumerable.Cast<object>() select Convert.ToString(value, CultureInfo.CurrentCulture), StringComparer.OrdinalIgnoreCase);
public override string ToString()
{
return Name;
}