0

I am only trying to return the date in my MVC application and have come across a problem. I have applied to my model DataFormatString = "{0:dd/M/yy}" and have also included ApplyFormatInEditMode = true as suggested from these posts ASP.NET MVC displaying date without time and Displaying Date only MVC

I am however generating the field to include the next 5 week commencing dates as shown here into a dropdownlist http://prntscr.com/ak825u.

This is done through the following code

  // GET: TimeSheets/Create
    public ActionResult Create()
    {

        int weekCount = 5;
        List<DateTime> listDates = new List<DateTime>();

        for (int i = 0; i < (weekCount * 7); ++i) //Get next 5 weeks
        {
            //Adds only next 5 mondays to the list of dates
            if (DateTime.Today.AddDays(i).DayOfWeek == DayOfWeek.Monday)
                listDates.Add(DateTime.Today.AddDays(i));
        }

        ViewData["DateList"] = new SelectList(listDates);

        return View();
    }

How would I go about removing the time to just display the date

Community
  • 1
  • 1
markabarmi
  • 245
  • 1
  • 14
  • It depends on what kind of web control you are using. .NET has no problem, but rendering is browser's responsibility. Alternately, you may populate a list of string instead of DateTime. – Jay Kim Mar 26 '16 at 11:47

2 Answers2

1

you need to set text and value in SelectList.

ViewData["DateList"] = new SelectList(listDates.Select(c => new SelectListItem() { Text = c.ToString("dd/mm/yy"), Value = c }));

in your View:

@Html.DropDownListFor(m => m.SelectedDate, (SelectList)ViewData["DateList"], "Select a date")

SelectedDate is a DateTime property in your model.

esiprogrammer
  • 1,438
  • 1
  • 17
  • 22
0

Esiprogrammer answer will work well, if you wanted to parse the date, this will be another option. Putting that attribute on your model wont work because you arent using the model to display the date, you are using viewdata to display the dates.

After you add a date and within your if condition add this: listDates[i] = ParseDate(DateTime.Today.ToString(), "MM/dd/yy");

Add the top answer helper class from this thread somewhere Display only Date in @Html.DisplayFor() in MVC

Community
  • 1
  • 1
Martin Dawson
  • 7,455
  • 6
  • 49
  • 92