ASP MVC 2: Error with dropdownlist on POST

Posted by wh0emPah on Stack Overflow See other posts from Stack Overflow or by wh0emPah
Published on 2010-05-02T18:42:42Z Indexed on 2010/05/02 18:47 UTC
Read the original article Hit count: 471

Filed under:
|
|
|
|

Okay i'm new to asp mvc2 and i'm experiencing some problems with the htmlhelper called Html.dropdownlistfor();

I want to present the user a list of days in the week. And i want the selected item to be bound to my model.

I have created this little class to generate a list of days + a short notation which i will use to store it in the database.

public static class days
{
    public static List<Day> getDayList()
    {
        List<Day> daylist = new List<Day>();

        daylist.Add(new Day("Monday", "MO"));
        daylist.Add(new Day("Tuesday", "TU"));
        // I left the other days out
        return daylist;
    }

    public class Dag{
        public string DayName{ get; set; }
        public string DayShortName { get; set; }

        public Dag(string name, string shortname)
        {
            this.DayName= name;
            this.DayShortName = shortname;
        }
    }
}

I really have now idea if this is the correct way to do it

Then i putted this in my controller:

SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
        ViewData["days"] = _list;
        return View("");

I have this line in my model

public string ChosenDay { get; set; }

And this in my view to display the list:

<div class="editor-field">
            <%: Html.DropDownListFor(model => model.ChosenDay, ViewData["days"] as SelectList, "--choose Day--")%>
        </div>

Now this all works perfect. On the first visit, But then when i'm doing a [HttpPost] Which looks like the following:

[HttpPost]
    public ActionResult Registreer(EventRegistreerViewModel model)
    {
       // I removed some unrelated code here 

       // The code below executes when modelstate.isvalid == false
        SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
        ViewData["days"] = _list;
        return View(model);
    }

Then i will have the following exception thrown:

The ViewData item that has the key 'ChosenDay' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

This errors gets thrown at the line in my view where i display the dropdown list.

I really have no idea how to solve this and tried several solutions i found online. but none of them really worked.

Ty in advance!

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc