我怎样才能重新使用我创建举行选择列表项code [英] How can I reuse code that I have created to hold a select list item

查看:95
本文介绍了我怎样才能重新使用我创建举行选择列表项code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,它是MVC视图模型

I have the following code that is a view model in MVC

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和在其他地方使用它加用它为我的选择下拉列表

I use the same combination of value and text in other places when I retrieve values and display the text equivalents. Is there some way that I can encapsulate this combination of value : texzt and use it in other places plus use it for my select drop down lists?

一个例子是,当我回到这是在一个视图psented $ P $的数据。该数据包含如0,1,2和3。不过,我要显示的文本值的状态codeS值。我可以创建另一个查找或硬code,但随后我会被复制的数据存储在两个不同的地方的方式。

One example is when I return data that's presented in a view. The data contains values for status codes such as 0,1,2 and 3. However I want to display the textual value. I could create another lookup or hardcode but then I would be duplicating the way the data is stored in two different places.

推荐答案

我建议你使用SelectLists和辅助方法 @ Html.DropDownListFor(M = GT; m.Status,新StatusSelectList() )在您的视图。

I recommend you to use SelectLists and the helper method @Html.DropDownListFor(m => m.Status, new StatusSelectList()) in your view.

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")
    {
    }
}

更新:

显示标签当前状态值:


  1. 装饰你属性与属性UIHint视图模型: [UIHint(DropDownList的)]

  2. 选择列表设置为 ViewBag.SelectLists =新词典&LT;字符串的SelectList&GT; {状态,新StatusSelectList()};

  3. 显示当前状态值的标签以 @ Html.DisplayFor(M = GT; m.Status)。

  1. Decorate you property in the view model with the UIHint attribute: [UIHint("DropDownList")].
  2. Set the select list to ViewBag.SelectLists = new Dictionary<string, SelectList> { "Status", new StatusSelectList() };
  3. Display the label for current status value with @Html.DisplayFor(m => m.Status).

这篇关于我怎样才能重新使用我创建举行选择列表项code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆