使用 MVC 5 C#。
我有一个列表对象。这是类对象:
public class CameraDevice
{
public string IPAddress { get; set; }
public string UDN { get; set; }
public string DocumentURL { get; set; }
public string FriendlyName { get; set; }
public bool IsUSB { get; set; }
public string Model { get; set; }
public string Make { get; set; }
public string DisplayName { get; set; }
}
使用此对象类型创建列表:
var devices = new List<CameraDevice>();
我想仅使用此列表对象中的 1 个字段填充下拉列表。
所以:
public ActionResult Connection()
{
var model = new ConnectionData();
model.Devices = new SelectList(devices.Select(i => new { i.FriendlyName }), "Device");
return View(model);
}
我的 View 模型类是:
public class ConnectionData
{
[Display(Name = "Device")]
[Required(ErrorMessage = "Select")]
public string SelectedDevice { get; set; }
public IEnumerable<SelectListItem> devices { get; set; }
}
我的 html5 标记是:
@Html.DropDownListFor(m => m.SelectedDevice, Model.Devices, "Select Device", new { @style = "width: 355px;height:21px; border:none;outline:0px;" });
问题是字段名称包含在下拉列表中:
如何删除字段名称?
最佳答案
您需要告诉用作 DropDownList 的值和文本的属性名称。
以这种方式使用 SelectList 构造函数:
model.Devices = new SelectList(devices
.Select(i => new { i.FriendlyName }),
"FriendlyName",
"FriendlyName");
第二个参数是 DropDownList 值字段,它将发布到表单提交时的操作,第二个参数是下拉列表的显示文本字段,因为您选择一个属性,所以我已将 FriendlyName
属性传递给这两个属性.
或者,如果您想使用带有一个参数的 SelectList 构造函数,在这种情况下,当您仅选择一个属性时,请勿在投影时创建匿名类型,因此只需这样做:
model.Devices = new SelectList(devices
.Select(i => i.FriendlyName));
关于c# - 删除 linq select 中的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867485/