LiranBo
LiranBo

Reputation: 2136

MVC multiple select List not showing default values

Been working on this issue for a few hours now, maybe I'm missing something simple here, but no matter what I try I can't get the default selected items to work.

The controller function:

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Room room = db.Rooms.Find(id);
    if (room == null)
    {
        return HttpNotFound();
    }
    List<int> allowedMods = new List<int> {1, 2};
    List<keyval> allMods = new List<keyval>
    {
        new keyval(1,"A"),
        new keyval(2,"B"),
        new keyval(3,"C")
    };
    MultiSelectList multiList = new MultiSelectList(allMods, "ID", "Name", allowedMods);
    ViewBag.mods = multiList;
    return View(room);
}

Simple helper class keyval:

public class keyval
{
    public int ID { get; set; }
    public string Name { get; set; }

    public keyval() { }
    public keyval(int ID, string Name)
    {
        this.ID = ID;
        this.Name = Name;
    }
}

The view:

@model X.Models.Room

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Room</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

        <div class="form-group">
            @Html.Label("Moderators Allowed", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.ListBox("mods", ViewBag.mods as MultiSelectList, new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Relevant generated Html:

<div class="col-md-10">
    <select class="form-control" id="mods" multiple="multiple" name="mods">
        <option value="1">A</option>
        <option value="2">B</option>
        <option value="3">C</option>
     </select>
</div>

I've tried so many different variations and when I submit the form I do get the new list of selected items, However the default values is not working for me.

I would really appreciate help on this issue.

Upvotes: 1

Views: 2168

Answers (1)

JB06
JB06

Reputation: 1931

The name of your listbox is the same as the name of your ViewBag property that holds the list, there is a strange bug with ViewBag that causes things to not render properly if this is the case. Try changing ViewBag.mods to ViewBag.moderators or something other than ViewBag.mods.

Tested using your code and that corrects the problem for me.

Upvotes: 4

Related Questions