![](/img/trans.png)
[英]How can i select item from a list view and assign it to a pictureBox?
[英]How can I reuse code that I have created to hold a select list item
我有以下代码,它是 MVC 中的视图 model
public class adminQViewModel
{
public SubTopic SubTopic { get; set; }
public Answer Answer { get; set; }
public string Status { get; set; }
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusType
{
get
{
return new[]
{
new SelectListItem { Value = "0", Text = "Release" },
new SelectListItem { Value = "1", Text = "Beta" },
new SelectListItem { Value = "2", Text = "Alpha" },
new SelectListItem { Value = "3", Text = "Draft" },
};
}
}
}
当我检索值并显示文本等效项时,我在其他地方使用相同的值和文本组合。 有什么方法可以封装这种价值组合: texzt 并在其他地方使用它,并将它用于我的 select 下拉列表?
一个例子是当我返回视图中显示的数据时。 数据包含状态代码的值,例如 0、1、2 和 3。但是我想显示文本值。 我可以创建另一个查找或硬编码,但是我将复制数据存储在两个不同位置的方式。
我建议您在视图中使用 SelectLists 和辅助方法@Html.DropDownListFor(m => m.Status, new StatusSelectList())
。
public class StatusSelectList : SelectList
{
private static Dictionary<int, string> data = new Dictionary<int, string>
{
{ 0, "Release" },
{ 1, "Beta" },
{ 2, "Alpha" },
{ 3, "Draft" }
};
public StatusSelectList()
: base(data, "Key", "Value")
{
}
}
更新:
显示 label 的当前状态值:
[UIHint("DropDownList")]
。ViewBag.SelectLists = new Dictionary<string, SelectList> { "Status", new StatusSelectList() };
@Html.DisplayFor(m => m.Status)
显示 label 的当前状态值。您可以在私有属性中设置一次,然后在每个后续请求中返回它。 这称为延迟加载:
private IEnumerable<SelectListItem> _statusType;
[DisplayName("Status")]
public IEnumerable<SelectListItem> StatusType
{
get
{
if (_statusType == null)
{
_statusType = new[] {
new SelectListItem { Value = "0", Text = "Release" },
new SelectListItem { Value = "1", Text = "Beta" },
new SelectListItem { Value = "2", Text = "Alpha" },
new SelectListItem { Value = "3", Text = "Draft" },
};
}
return _statusType;
}
}
此外,如果您在不同的用户会话之间重用相同的列表,那么将其设置为 static 属性可能是有意义的,以便它被实例化一次并一直存在,直到应用程序池被回收/重新启动。
更新:
您可以使用一点点 LINQ 来检索您想要的文本。 例如,要根据值 2 获取“Alpha”:
string text = StatusType.SingleOrDefault(s => s.Value == "2");
编写自定义 class:
public class StatusType : IEnumerable<KeyValuePair<int, string>>
{
private readonly List<KeyValuePair<int, string>> entries = new List<KeyValuePair<int, string>>();
public void Add(int key, string value)
{
this.entries.Add(new KeyValuePair<int, string>(key, value));
}
public string this[int key]
{
get
{
foreach (var kvp in this.entries)
{
if (string.Compare(kvp.Key, key, StringComparison.Ordinal) == 0)
{
return kvp.Value;
}
}
return null;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.