0

I had a look at this:

ASP.NET MVC - How to pass an Array to the view?

and am struggeling with deploying my DateTime[] as a dropdownlist in the view, herewith my line but it is not correct:

<p style="color:Red"><%: Html.DropDownList("Choose a Sunday: ", (IEnumerable<SelectListItem>)ViewData["Sundays"], "--Select--")%>
</p>

In the controller i have:

[HttpGet]
public ActionResult MyAction()
{
  DateTime[] allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);
  ViewData["Sundays"] = allSundaysInMonth;
  return View();
}

can someone help please? thanks

Community
  • 1
  • 1
charlie_cat
  • 1,830
  • 7
  • 44
  • 73

3 Answers3

1

Perhaps what you want to do is this:

[HttpGet]
public ActionResult MyAction()
{
  IEnumerable<SelectListItem> allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now).Select(day => new SelectListItem() { Text = day.ToString(), Value = day.ToString() });
  ViewData["Sundays"] = allSundaysInMonth;
  return View();
}

That is depending on your display format. What I'm trying to point out is that DateTime and SelectListItem may not have an implicit cast, so you get a type mismatch at runtime.

eburgos
  • 2,022
  • 17
  • 11
  • yup I would like to keep my type in the controller as DateTime[] though and cast in the view rather? – charlie_cat Aug 03 '12 at 13:41
  • sure, in that case: `

    <%: Html.DropDownList("Choose a Sunday: ", ((DateTime[])ViewData["Sundays"]).Select(day => new SelectListItem() { Text = day.ToString(), Value = day.ToString() }), "--Select--")%>

    `. Also consider Shyju's point of view.
    – eburgos Aug 04 '12 at 21:23
1

If you ever think (realize) dynamic magic variables like ViewData/ ViewBag is an evil and thinking about using strongly typed ViewModel for your view, you can do like this

create a ViewModel specific for your View (UI).

public class EventViewModel
{
  public IEnumerable<SelectListItem> AllSundays { set;get;}
  public string SelectedSunday { set;get;}
}

In your action method, set the value and send it to the view

public ActionResult MyAction()
{
  var vm=new EventViewModel();
  vm.AllSundays = GetDatesOfSundays(System.DateTime.Now).
          Select(d => new SelectListItem() {
            Text = d.ToString(), Value = d.ToString() }).ToList();

  return View(vm);
}

Change your view like this

@model EventViewModel
@Html.DropDownListFor(x => x.SelectedSunday, Model.AllSundays, "--Select One--")

ViewBag/ViewData is bad. It makes your code ugly. Stick to strongly typed.

Shyju
  • 214,206
  • 104
  • 411
  • 497
0

You cast the list to IEnumerable<SelectListItem>, but its a list of DateTimes. Casting the list to IEnumerable<DateTime> should fix it.

Or you might want to put list of SelectListItem on the ViewData instead!

Arcturus
  • 26,677
  • 10
  • 92
  • 107