Frage

This is my code to display List of Names in MultiSelectList

Controller

// GET
public ActionResult Create()
{
    var bookViewModel = new BookViewModel
    {
        AuthorList = _Authors.GetAuthors()
                          .Select(a => new SelectListItem { 
                                     Value = a.Id.ToString(), 
                                     Text = a.Name }
                                 ).ToList()
    };

    return View(bookViewModel);
}

// POST
[HttpPost]
public ActionResult Create(BookViewModel model)
{
    if (ModelState.IsValid)
    {
        //Some code
    }
    else
    {
        return View(model);
    }
}

View

@using (Html.BeginForm())
{
    ...
    @Html.ListBoxFor(m => m.AuthorIds, Model.AuthorList, new { multiple = "multiple" })
    <input id="btnCreate" type="submit" value="Create" />
}

This code works fine when if Model validetes, but if ModelState.IsValid = false, when it returns the model back to the view (.. else { return View(model); }), model does not contain the AuthorList and shows an error

There is no ViewData item of type 'IEnumerable' that has the key 'AuthorIds'.

in the view line @Html.ListBoxFor(m => m.AuthorIds, Model.AuthorList....

Any idea how to fix this?

War es hilfreich?

Lösung

You need to initialize authorlist again in your else part

else
    {
model.AuthorList = _Authors.GetAuthors()
                          .Select(a => new SelectListItem { 
                                     Value = a.Id.ToString(), 
                                     Text = a.Name }
                                 ).ToList()
        return View(model);
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top