设置选择列表中项目的格式

发布于 2024-10-14 22:55:23 字数 452 浏览 2 评论 0原文

我看过其他帖子,其中有对此问题的答案,但我无法让其中任何一个为我工作......所以。这是在我的控制器中->

ViewData["TARGET_DATE"] = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE");

我希望能够对从数据库返回的日期应用一种格式,我的 DDL 看起来像这样,

<td><%=Html.DropDownList("TARGET_DATE", "All")%></td>

有人知道是否有一种方法可以循环遍历并格式化每个日期,或者对所有日期应用一种格式。或者最好的方法是什么,如果您需要我可以提供的更多代码,我真正想要的是显示日期而不显示时间。提前致谢。

i have seen other posts with answers to this but i cannot get any of them to work for me.. so. this is in my controller->

ViewData["TARGET_DATE"] = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE");

i want to be able to apply a format on the dates that come back from the db, my DDL looks like this

<td><%=Html.DropDownList("TARGET_DATE", "All")%></td>

does anyone know if there is a way to loop through and format each date, or apply a format to them all. or what would be the best way to do this, if u need more code i can provide, what i really want is to display the date without the time with it. thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别闹i 2024-10-21 22:55:23

我知道这篇文章很旧,但我在寻找同一问题的答案时遇到了它。我最终编写了一个 FormattableSelectList 类,它采用格式字符串作为参数,然后格式化选择列表的输出。这是如何使用它的示例。

@Html.DropDownFor(
    o => o.SomeProperty,
    new FormattableSelectList(ViewBag.MyItems, "ID", "Time", "{0:f}"),
    "Choose a Time"
)

我在 http: //www.jpolete.me/2011/11/16/a-formattable-selectlist-for-net-mvc/。这是它的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Web.UI;
using System.Globalization;

public class FormattableSelectList : SelectList
{
    private string _FormatString;

    public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString)
        : base(items, dataValueField, dataTextField)
    {
        _FormatString = formatString;
    }

    public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString, object selectedValue)
        : base(items, dataValueField, dataTextField, selectedValue)
    {
        _FormatString = formatString;
    }

    public override IEnumerator<SelectListItem> GetEnumerator()
    {
        return ((!String.IsNullOrEmpty(DataValueField)) ?
            GetListItemsWithValueField() :
            GetListItemsWithoutValueField()).GetEnumerator();
    }

    private IList<SelectListItem> GetListItemsWithValueField()
    {
        HashSet<string> selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (SelectedValues != null)
        {
            selectedValues.UnionWith(from object value in SelectedValues select Convert.ToString(value, CultureInfo.CurrentCulture));
        }

        var listItems = from object item in Items
                        let value = Eval(item, DataValueField, null)
                        select new SelectListItem
                        {
                            Value = value,
                            Text = Eval(item, DataTextField, _FormatString),
                            Selected = selectedValues.Contains(value)
                        };
        return listItems.ToList();
    }

    private IList<SelectListItem> GetListItemsWithoutValueField()
    {
        HashSet<object> selectedValues = new HashSet<object>();
        if (SelectedValues != null)
        {
            selectedValues.UnionWith(SelectedValues.Cast<object>());
        }

        var listItems = from object item in Items
                        select new SelectListItem
                        {
                            Text = Eval(item, DataTextField, _FormatString),
                            Selected = selectedValues.Contains(item)
                        };
        return listItems.ToList();
    }

    private static string Eval(object container, string expression, string formatString)
    {
        object value = container;
        if (!String.IsNullOrEmpty(expression))
        {
            value = DataBinder.Eval(container, expression);
        }
        string stringValue;
        if (formatString == null)
        {
            stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
        }
        else
        {
            stringValue = String.Format(formatString, value);
        }

        return stringValue;
    }

}

I know this post is old, but I ran across it while searching for an answer to the same problem. I ended up writing a FormattableSelectList class that takes a format string as a parameter, and then formats that output of the select list. Here's a sample of how to use it.

@Html.DropDownFor(
    o => o.SomeProperty,
    new FormattableSelectList(ViewBag.MyItems, "ID", "Time", "{0:f}"),
    "Choose a Time"
)

I wrote a short post about it at http://www.jpolete.me/2011/11/16/a-formattable-selectlist-for-net-mvc/. Here's the code for it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Web.UI;
using System.Globalization;

public class FormattableSelectList : SelectList
{
    private string _FormatString;

    public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString)
        : base(items, dataValueField, dataTextField)
    {
        _FormatString = formatString;
    }

    public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString, object selectedValue)
        : base(items, dataValueField, dataTextField, selectedValue)
    {
        _FormatString = formatString;
    }

    public override IEnumerator<SelectListItem> GetEnumerator()
    {
        return ((!String.IsNullOrEmpty(DataValueField)) ?
            GetListItemsWithValueField() :
            GetListItemsWithoutValueField()).GetEnumerator();
    }

    private IList<SelectListItem> GetListItemsWithValueField()
    {
        HashSet<string> selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (SelectedValues != null)
        {
            selectedValues.UnionWith(from object value in SelectedValues select Convert.ToString(value, CultureInfo.CurrentCulture));
        }

        var listItems = from object item in Items
                        let value = Eval(item, DataValueField, null)
                        select new SelectListItem
                        {
                            Value = value,
                            Text = Eval(item, DataTextField, _FormatString),
                            Selected = selectedValues.Contains(value)
                        };
        return listItems.ToList();
    }

    private IList<SelectListItem> GetListItemsWithoutValueField()
    {
        HashSet<object> selectedValues = new HashSet<object>();
        if (SelectedValues != null)
        {
            selectedValues.UnionWith(SelectedValues.Cast<object>());
        }

        var listItems = from object item in Items
                        select new SelectListItem
                        {
                            Text = Eval(item, DataTextField, _FormatString),
                            Selected = selectedValues.Contains(item)
                        };
        return listItems.ToList();
    }

    private static string Eval(object container, string expression, string formatString)
    {
        object value = container;
        if (!String.IsNullOrEmpty(expression))
        {
            value = DataBinder.Eval(container, expression);
        }
        string stringValue;
        if (formatString == null)
        {
            stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
        }
        else
        {
            stringValue = String.Format(formatString, value);
        }

        return stringValue;
    }

}
南七夏 2024-10-21 22:55:23

这是我如何实现上面的类。我的客户正在寻找两个包含开始时间和结束时间的下拉列表。在 MVC4

模型中:

    [Display(Name = "Time (From):")]        
    public int FromTimeId { get; set; }

    [Display(Name = "Time (To):")]        
    public int ToTimeId { get; set; }

    public virtual FromTime FromTime { get; set; }
    public virtual ToTime ToTime { get; set; }      

控制器:

    public ActionResult Create()
   {          
        ViewBag.FromTimes = db.FromTimes;
        ViewBag.ToTimes = db.ToTimes;
   }

视图:

  <div class="editor-field">
                        @Html.DropDownListFor(model => model.FromTimeId, new Namespace.FormattableSelectList(ViewBag.FromTimes, "FromTimeId", "FromTimeName", "{0:h:mm tt}"))<br />                        
                        @Html.ValidationMessageFor(model => model.FromTimeId)
                    </div>
                </td>
                <td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.ToTimeId, "To Time:")
                    </div>
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.ToTimeId, new Namespace.FormattableSelectList(ViewBag.ToTimes, "ToTimeId", "ToTimeName", "{0:h:mm tt}"))<br />                        
                        @Html.ValidationMessageFor(model => model.ToTimeId)
                    </div>

Here is how I implemented the class above. My client was looking for two dropdownlists containing Start time and End time. In MVC4

Model:

    [Display(Name = "Time (From):")]        
    public int FromTimeId { get; set; }

    [Display(Name = "Time (To):")]        
    public int ToTimeId { get; set; }

    public virtual FromTime FromTime { get; set; }
    public virtual ToTime ToTime { get; set; }      

Controller:

    public ActionResult Create()
   {          
        ViewBag.FromTimes = db.FromTimes;
        ViewBag.ToTimes = db.ToTimes;
   }

View:

  <div class="editor-field">
                        @Html.DropDownListFor(model => model.FromTimeId, new Namespace.FormattableSelectList(ViewBag.FromTimes, "FromTimeId", "FromTimeName", "{0:h:mm tt}"))<br />                        
                        @Html.ValidationMessageFor(model => model.FromTimeId)
                    </div>
                </td>
                <td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.ToTimeId, "To Time:")
                    </div>
                    <div class="editor-field">
                        @Html.DropDownListFor(model => model.ToTimeId, new Namespace.FormattableSelectList(ViewBag.ToTimes, "ToTimeId", "ToTimeName", "{0:h:mm tt}"))<br />                        
                        @Html.ValidationMessageFor(model => model.ToTimeId)
                    </div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文