Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining multiple classes in a MVC4 view

Let's say I have a model like this (simplified from the original):

public class Location
{
    public int ID { get; set; }
    public string BinNumber { get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Description { get; set; }
    public virtual Location Bin { get; set; }
}

public class LineOnPickList
{
    public int ID { get; set; }
    public virtual Item Item { get; set; }
}

The usual thing to do here on the LineOfPickList Create view would be to have a dropdownlist that listed all the Item Descriptions and put the selected item in the newly created LineOnPickList record when Create was clicked.

What I need to do however is show a dropdownlist of Location BinNumbers, yet still have the Item associated with that Location in the newly created LineOnPickList record.

How would that be done?

like image 487
davecove Avatar asked Dec 17 '25 03:12

davecove


1 Answers

Define a view model for your drop down

public class ItemViewModel
{
    public int ID { get; set; }
    public string BinNumber { get; set; }
}

Then build the drop down list data in your controller action as follows

public class CreateLineOnPickListViewModel
{
    public int ItemId { get; set; }
    public IEnumerable<ItemViewModel> Items { get; set; }
}

public ActionResult Create()
{
    var model = new CreateLineOnPickListViewModel();
    model.Items = db.Items
          .Select(i => new ItemViewModel { ID = i.ID, BinNumber = i.Bin.BinNumber });

    return View(model);
}

Then in your view

@model CreateLineOnPickListViewModel

@Html.DropDownListFor(m => m.ItemId, new SelectList(Model.Items, "ID", "BinNumber"), "-")

Then your post action method in your controller would look like this

public ActionResult Create(CreateLineOnPickListViewModel model)
{
    var item = new Item { ID = model.ItemID };
    db.Items.Attach(item);

    var lineOnPickList = new LineOnPickList { Item = item };

    db.SaveChanges();

    return View(model);
}
like image 123
Eranga Avatar answered Dec 19 '25 20:12

Eranga