如何使用Html.DropDownListFor(...)格式化日期时间

时间:2015-06-08 13:47:38

标签: asp.net-mvc html.dropdownlistfor

我想要一个带有短日期格式的dropdownList。 但以下都不起作用。 我有

[Property]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? DepartrueDate { get; set; }

在视图中,我尝试了

<div>@Html.DropDownListFor(m => m.TripDepartures.First().DepartrueDate, new SelectList(Model.TripDepartures.Select(s=>
         new SelectListItem { Value = s.Id.ToString(), Text = s.DepartrueDate.Value.ToShortDateString() }).ToList()))</div>
</div>

它没有输出; 我也试过

 <div>@Html.DropDownListFor(m => m.TripDepartures.First().DepartrueDate, new SelectList(Model.TripDepartures, "Id","DepartrueDate"))</div>
                </div>

它给出enter image description here
我怎么能得到一个短暂的约会?

3 个答案:

答案 0 :(得分:1)

理想情况下,您不希望将域实体(TripDepartures)传递给View from Controller。这不是一个好的设计实践。

相反,您想要传递 SelectListItem

enter image description here

视图

@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.SelectedTripDepartureId, Model.AvailableTripDepartures)
    <input type="submit" value="Submit" />
}

模型

public class HomeModel
{
    public int SelectedTripDepartureId { get; set; }
    public IList<SelectListItem> AvailableTripDepartures { get; set; }

    public HomeModel()
    {
        AvailableTripDepartures = new List<SelectListItem>();
    }
}

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        HomeModel model = new HomeModel();
        model.AvailableTripDepartures = GetTripDepartures()
            .Select(s => new SelectListItem
            {
                Value = s.Id.ToString(),
                Text = s.DepartrueDate.Value.ToString("MM/dd/yyyy")
            }).ToList();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(HomeModel model)
    {
        int tripDepartureId = model.SelectedTripDepartureId;

        DateTime? departrueDate = GetTripDepartures()
            .Where(x => x.Id == tripDepartureId)
            .Select(x => x.DepartrueDate)
            .FirstOrDefault();

        return View(model);
    }

    // This data will be from persistent storage such as database.
    private IList<TripDeparture> GetTripDepartures()
    {
        return new List<TripDeparture>
        {
            new TripDeparture {Id = 1, DepartrueDate = DateTime.Now.AddDays(1)},
            new TripDeparture {Id = 2, DepartrueDate = DateTime.Now.AddDays(2)},
            new TripDeparture {Id = 3, DepartrueDate = DateTime.Now.AddDays(3)},
        };
    }
}

TripDeparture Class

public class TripDeparture
{
    public int Id { get; set; }
    public DateTime? DepartrueDate { get; set; }
}

答案 1 :(得分:1)

不应该是:

@Html.DropDownListFor(m => m.TripDepartures.First().Id.ToString(), new SelectList(Model.TripDepartures.Select(s=>
     new SelectListItem() { Value = s.Id.ToString(), Text = s.DepartrueDate.Value.ToShortDateString() }).ToList()))

如果不起作用: 你确定Model.TripDepartures有元素吗?

我记得我自己在模型中添加了几次SelectList,因此您可以尝试在Model中添加一个属性,即SelectList类型。您可以为每个DepartureDate添加一个SelectListItem,自己设置id和值,并自行循环和调试。它与你的Linq代码基本相同,但我记得我之所以这样做是因为这个原因。

Model.DepartureDateSelectList = new SelectList();
foreach (TripDeparture tripDeparture in Model.TripDepartures) {
{
    SelectListItem item = new SelectListItem();
    item.Value = tripDeparture.Id.ToString();
    item.Text = tripDeparture.DepartueDate.Value.ToShortDateString(); //Didn't do a null check, since you didn't do it in you code either. You should change DataType to non-nullable or perform a check and handle if it's null
    Model.DepartureDateSelectList.Add(item);
}

如果您确实看到了列表但未设置默认选定项目,则将建议的更改应用于所选项目表达式。如果仍未正确设置,您可以自行在循环中设置所选属性。 DropDownListFor中存在一个错误,导致所选项目并未始终设置。

答案 2 :(得分:0)

您可以欺骗系统并绑定到字符串字段而不是日期字段:

[Property]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? DepartrueDate { get; set; }

public string DepartrueDateText { get { return DepartrueDate.ToShortDataString(); } }

不要忘记你的空检查。 :)

我为枚举字段做了很多工作,以便识别[Display(Name =“”)]属性。