Reputation: 1289
I have a form where one field should be a collection of objects (0 or more) from another table using combox/multiple-select dropdown, what is the best practice to establish this? e.g:
public class Person{
public int PersonId { get; set; }
public string PersonName { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
///or
public IList<Address> Addresses { get; set; }
///or
public IEnumerable<Addresses > Addresses { get; set; }
}
thanks
Upvotes: 1
Views: 201
Reputation: 367
One way to do it is to populate your address list in your controller and use the Html.DropDownList helper to create your drop down.
For example:
public ActionResult Index()
{
var addressList = <YourAddressListHere>;
ViewData["Addresses"] = new SelectList(addressList, "<ValueProperty>", "<NameProperty>");
return View();
}
And in your view (Razor syntax):
@Html.DropDownList("AddressDropDown", (ViewData["Addresses"] as SelectList))
There is also Html.ListBoxFor and Html.ListBox helpers if you wanted to do multi-select. The same basic approach applies.
(EDIT) Sorry for my misunderstanding.
To get the list of addresses that were selected you can add the control name as a parameter in you "POST" handler and extract them during the save/edit/insert function.
[HttpPost]
public ActionResult Edit(int[] addressList, <your parameters>)
.....
with the UI code as:
<div class="editor-field">
@Html.ListBox("addressList")
</div>
You can do whatever you need with the list of address ID's that were selected. I know that there is more than likely a better way to do this with MVC. If anyone looks at this and knows a better way, please comment because I'd like to know myself. I know that you can create some custom binder classes that I think will do all of this stuff automatically, but I haven't gotten that far yet with MVC. I, myself, am a beginner with MVC.
In any case, I hope this helps a bit.
Upvotes: 2