0

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.

2 Answers 2

2

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;
    }

}
1
  • That is quite a bit more succinct, huh? :)
    – jpolete
    Sep 19, 2014 at 17:52
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.