Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Super simple implementation of multiselect list box in Edit view

Using MVC4 here with EF and CF (badly)

I have a class like this:

public class Feature
{
    public int ID { get; set; }
    public string Desc { get; set; }
}

And one like this:

public class Device   //change to Devices
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Feature> Features { get; set; }
}

On the Edit view for the Device model I would like for there to be a ListBox that contains all elements of the Feature model (Desc property displayed) with those features contained in the device.Features collection pre-selected.

Then, when the user clicks Save on the Edit view, the current collection of selected items in the ListBox gets written back to the device's Features collection.

What does the controller code and cshtml look like for this trick?

Thank you for your time, Dave

like image 339
davecove Avatar asked Dec 02 '22 22:12

davecove


1 Answers

As always you could start by writing a view model that will meet the requirements of the view you described:

public class EditDeviceViewModel
{
    public IEnumerable<int> SelectedFeatures { get; set; }
    public IEnumerable<SelectListItem> Features { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }
}

and then your controller:

public class DeviceController : Controller
{
    public ActionResult Edit(int id)
    {
        Device device = (go get your device from your repository using the id)
        IList<Feature> features = (go get all features from your repository)

        // now build the view model
        var model = new EditDeviceViewModel();
        model.ID = device.ID;
        model.Name = device.Name;
        model.SelectedFeatures = device.Features.Select(x => x.ID);
        model.Features = features
            .Select(x => new SelectListItem
            {
                Value = x.ID.ToString(),
                Text = x.Name,
            })
            .ToList();

        // pass the view model to the view
        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(EditDeviceViewModel model)
    {
        // model.SelectedFeatures will contain the selected feature IDs here
        ...
    }
}

and finally the view:

@model EditDeviceViewModel

@using (Html.BeginForm())
{
    @Html.Html.HiddenFor(x => x.ID)
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
    </div>
    <div>
        @Html.LabelFor(x => x.SelectedFeatures)
        @Html.ListBoxFor(x => x.SelectedFeatures, Model.Features)
    </div>

    <button type="submit">Edit</button>
}
like image 165
Darin Dimitrov Avatar answered Dec 24 '22 15:12

Darin Dimitrov