Asp.net mvc dropdown list - asp.net-mvc

I am having a bugger of a time trying to figure out where I am going wrong. Scenario is this. Trying to add an object that has a foreign key in it with mvc entity framework.
public class Person
{
[Key]
public virtual int PersonId { get; set; }
[Display(Name = "First Name")]
[Required]
[MaxLength(50)]
public virtual string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required]
[MaxLength(50)]
public virtual string LastName { get; set; }
[Required]
public virtual int TestItem { get; set; }
[Required(ErrorMessage = "Please Select an Employee Type")]
public virtual EmployeeType EmployeeTypeId { get; set; }
}
public class EmployeeType
{
[Key]
public virtual int EmployeeTypeId { get; set; }
[Required]
public virtual string EmployeeTypeName { get; set; }
}
Those are the two pocos for the entities.
public ActionResult Create()
{
PersonViewModel pv = new PersonViewModel();
ViewBag.EmployeeTypeSelect= new SelectList(db.EmployeeTypes, "EmployeeTypeId", "EmployeeTypeName");
return View(pv);
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(PersonViewModel personVM)
{
if (ModelState.IsValid)
{
Person person = new Person();
person.EmployeeTypeId = personVM.EmployeeTypeId;
person.FirstName = personVM.FirstName;
person.LastName = personVM.LastName;
person.TestItem = personVM.TestItem;
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(personVM);
}
That is the controller.
#model MvcApplication3.Models.PersonViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>PersonViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TestItem)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TestItem)
#Html.ValidationMessageFor(model => model.TestItem)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeeTypeId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model=>model.EmployeeTypeId,(SelectList)ViewBag.EmployeeTypeSelect)
#Html.ValidationMessageFor(model => model.EmployeeTypeId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
That is the view.
Everything works fine with the view off the initial get, but when I post the EmployeeTypeId has a null value. I check the source and the select list is fine, has proper values and text. Please help as I have no clue where i am going wrong.
Thanks

Try adding in Html.EndForm() in the HTML after all of the values you wish to post and see if that fixes the problem?

Your Person and EmployeeType class needs to have a default (empty) constructor for the model binding to work -
public class EmployeeType
{
[Key]
public virtual int EmployeeTypeId { get; set; }
[Required]
public virtual string EmployeeTypeName { get; set; }
public EmployeeType()
{
}
}
public class Person {
[Key]
public virtual int PersonId { get; set; }
[Display(Name = "First Name")]
[Required]
[MaxLength(50)]
public virtual string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required]
[MaxLength(50)]
public virtual string LastName { get; set; }
[Required]
public virtual int TestItem { get; set; }
[Required(ErrorMessage = "Please Select an Employee Type")]
public virtual EmployeeType EmployeeTypeId { get; set; }
public Person()
{
EmployeeTypeId = new EmployeeType();
}
}
Also, try in your view, making it
#Html.DropDownListFor(model=>model.EmployeeTypeId.EmployeeTypeId,(SelectList)ViewBag.EmployeeTypeSelect)

Related

Unable to populate checkbox from database data in mvc 4

This is my Controller code.
public ActionResult Create()
{
ViewBag.grp_id = new SelectList(db.tm_grp_group, "grp_id", "grp_name");
ViewBag.perm_id = new SelectList(db.tm_perm_level, "perm_id", "perm_levelname");
return View();
}
Below is my view code.
#model Permission.ts_grp_perm_mapping
....
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ts_grp_perm_mapping</legend>
<div class="editor-label">
#Html.LabelFor(model => model.grp_permid)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.grp_permid)
#Html.ValidationMessageFor(model => model.grp_permid)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.grp_id, "tm_grp_group")
</div>
<div class="editor-field">
#Html.DropDownList("grp_id", String.Empty)
#Html.ValidationMessageFor(model => model.grp_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.perm_id, "tm_perm_level")
</div>
<div class="editor-field">
#Html.DropDownList("perm_id", String.Empty)
#Html.ValidationMessageFor(model => model.perm_id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In controller ViewBag.perm_id contains some values (this is foreign key). In view perm.id displays in the form of dropdownbox but I want it in the form of checkboxlist. How can I achieve this?
This is the viewmodel I created.
public class AssignUserViewModel
{
public tm_perm_level[] perms { get; set; }
public int grp_id { get; set; }
}
Now in controller how can i send values to view? This is my tm_perm_level model
public partial class tm_perm_level
{
public tm_perm_level()
{
this.ts_grp_perm_mapping = new HashSet<ts_grp_perm_mapping>();
}
public int perm_id { get; set; }
public string perm_levelname { get; set; }
public string perm_description { get; set; }
public bool perm_status { get; set; }
public virtual ICollection<ts_grp_perm_mapping> ts_grp_perm_mapping { get; set; }
}
This is ts_grp_perm_mapping model
public partial class ts_grp_perm_mapping
{
public ts_grp_perm_mapping()
{
this.ts_perm_levelmapping = new HashSet<ts_perm_levelmapping>();
}
public int grp_permid { get; set; }
public int grp_id { get; set; }
public int perm_id { get; set; }
public List<tm_perm_level> permissions { get; set; }
public virtual tm_grp_group tm_grp_group { get; set; }
public virtual tm_perm_level tm_perm_level { get; set; }
public virtual ICollection<ts_perm_levelmapping> ts_perm_levelmapping { get; set; }
}
Especially when editing, always start with view models to represent what you want to display (refer What is ViewModel in MVC?)
public class PermissionVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class GroupPermissionVM
{
public int GroupID { get; set; }
public IEnumerable<SelectListItem> GroupList { get; set; }
public IEnumerable<PermissionVM> Permissions { get; set; }
}
Then create an EditorTemplate for PermissionVM. In the /Views/Shared/EditorTemplates/PermissionVM.cshtml folder
#model PermissionVM
<div>
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.Name)
#Html.CheckBoxFor(m => m.IsSelected)
#Html.LabelFor(m => m.IsSelected, Model.Name)
</div>
and the main view will be
#model GroupPermissionVM
....
#using (Html.BeginForm())
{
// dropdownlist
#Html.LabelFor(m => m.GroupID)
#Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select")
#Html.ValidationMessageFor(m => m.GroupID)
// checkboxlist
#Html.EditorFor(m => m.Permissions)
<input type="submit" value="Create" />
}
The controller methods would then be
public ActionResult Create()
{
var groups = db.tm_grp_group;
var permissions = db.tm_perm_level;
GroupPermissionVM model = new GroupPermissionVM
{
GroupList = new SelectList(groups, "grp_id", "grp_name"),
Permissions = permissions.Select(p => new PermissionVM
{
ID = p.perm_id,
Name = p.perm_levelname
}
};
return View(model);
}
[HttpPost]
public ActionResult Create(GroupPermissionVM model)
{
if (!ModelState.IsValid)
{
var groups = db.tm_grp_group;
model.GroupList = new SelectList(groups, "grp_id", "grp_name");
return View(model);
}
// map the view model to a new instance of your data model(s)
// note: to get the ID's of the selected permissions -
// var selectedPermissions = model.Permissions.Where(p => p.IsSelected).Select(p => p.ID);
// save and redirect
}
Side note: I strongly recommend you follow normal naming conventions
Edit
Based on OP's comment for an option using radio buttons to select only one item, the revised code would be
public class PermissionVM
{
public int ID { get; set; }
public string Name { get; set; }
}
public class GroupPermissionVM
{
public int GroupID { get; set; }
public int PermissionID { get; set; }
public IEnumerable<SelectListItem> GroupList { get; set; }
public IEnumerable<PermissionVM> Permissions { get; set; }
}
and the view would be (no separate EditorTemplate required)
#model GroupPermissionVM
....
#using (Html.BeginForm())
{
// dropdownlist as above
// radio buttons
foreach (var permission in Model.Permissions)
{
<label>
#Html.RadioButtonForm(m => m.PermissionID, permission.ID)
<span>#permission.Name</span>
</label>
}
<input type="submit" value="Create" />
}
and in the POST method, the value of model.PermissionID will contain the ID of the selected Permission.

DropDownListFor Validation Always fires on edit

I have two DropDownListFor elements on a edit view. Even though, value is selected in dropdown, it always fires the DropDownListFor required field validation When i try to submit the view.
public class propertyTypeModel
{
public int type_id { get; set; }
[Required(ErrorMessage = "Property Type Required")]
[Display(Name = "Type")]
public string property_type { get; set; }
}
public class propertyStatusModel
{
public int status_id { get; set; }
[Required(ErrorMessage = "Status Required")]
[Display(Name = "Status")]
public string property_status { get; set; }
}
public class propertyModel
{
public int id { get; set; }
[Display(Name = "Property Type")]
public propertyTypeModel property_type { get; set; }
[Display(Name = "Property Type")]
[Required]
public List<propertyTypeModel> property_type_lst { get; set; }
[Display(Name = "Property Status")]
public propertyStatusModel property_status { get; set; }
[Display(Name = "Property Status")]
[Required]
public List<propertyStatusModel> property_status_lst { get; set; }
}
public ActionResult Edit(int id)
{
rep=new propertyRepository();
propertyModel model = new propertyModel();
model.id = id;
model.property_type_lst = getPropertyTypes();//load dropdown values
model.property_status_lst = getPropertyStatus();//load dropdown values
return View(model);
}
[HttpPost]
public ActionResult Edit(int id, propertyModel model)
{
try
{
model.property_type_lst = getPropertyTypes();
model.property_status_lst = getPropertyStatus();
model.property_owner_lst = getPropertyOwners();
if (ModelState.IsValid)
{
rep = new propertyRepository();
rep.Update(model);
return RedirectToAction("Index");
}
return View(model);
}
catch
{
return View();
}
}
#model RealEstateApp.Models.propertyModel
<div class="editor-label">
#Html.LabelFor(model => model.property_type_lst)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.property_type.type_id, new SelectList(Model.property_type_lst, "type_id", "property_type"),"Select Below...")
#Html.ValidationMessageFor(model => model.property_type_lst)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.property_status_lst)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.property_status.status_id, new SelectList(Model.property_status_lst, "status_id", "property_status"),"Select Below...")
#Html.ValidationMessageFor(model => model.property_status_lst)
</div>
Try
<div class="editor-field">
#Html.DropDownListFor(model.property_type_lst, new SelectList(Model.property_type_lst, "type_id", "property_type"),"Select Below...", new {id = Model.property_type.type_id})
#Html.ValidationMessageFor(model => model.property_type_lst)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.property_status_lst)
</div>
<div class="editor-field">
#Html.DropDownListFor(model.property_status_lst, new SelectList(Model.property_status_lst, "status_id", "property_status"),"Select Below...", new {id = Model.property_status.status_id})
#Html.ValidationMessageFor(model => model.property_status_lst)
</div>

How to Creating View And View Model For Two Related Entity

i have two entity:
1) student
and 2) address.
public class Student
{
Public Int StudentId { get; set; }
Public String FullName { get; set; }
Public virtual IList<Address> Addresses { get; set; }
}
public class Address
{
Public Int AddressId { get; set; }
Public Int StudentId { get; set; }
Public String FullAddress { get; set; }
Public virtual Student Student { get; set; }
}
each student may have zero or more address.
i want to create single view for this two entity. i know that must create a view model. this is view model.
public class StudentViewModel
{
Public Int StudentId { get; set; }
Public String FullName { get; set; }
public Address AddAddressModel { get; set; }
Public virtual IList<Address> Addresses { get; set; }
}
and i create a view for StudentViewModel. this is StudentViewModel:
#model MyProject.Models.StudentViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm ())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FullName)
#Html.ValidationMessageFor(model => model.FullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddAddressModel.FullAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddAddressModel.FullAddres)
#Html.ValidationMessageFor(model => model.AddAddressModel.FullAddres)
</div>
<button id="add">add address to list</button>
<input type="submit" value="save in database" />
</fieldset>
please tell me how i can add one or more address on by one in Addresses Property of StudentViewModel and show after this operation to user. finally when i click on the "save in database" button student and his addresses must be inserted in database.
I have in the past submitted nested child entities, but that was always done with an API call and the form was serialized to a JSON object before submission.
Because you only really need multiple FullAddress values, you could change your model and view accordingly (not tested):
Model:
public class StudentViewModel
{
public int StudentId { get; set; }
public string FullName { get; set; }
public string[] Addresses { get; set; }
}
View:
In your view, when you click the 'Add' button, make sure that (through JavaScript) you end up with something like this:
<textarea name="Addresses[]">Some Address 1</textarea>
<textarea name="Addresses[]">Some Address 2</textarea>
etc...
you can try using:
#EditorFor(m => model.Addresses)
this will create template for your address model

UI elements from several model properties in ASP.NET MVC

I've been doing some searches, found this ASP.NET MVC 3 - Partial vs Display Template vs Editor Template but I am still not clear as what and how should I use for "custom UI controls" for several model properties.
I have two examples in mind:
FistName MiddleInitial LastName
or Phone Ext
I want to have some sort of a re-usable UI control / template that I can use.
Say, I have a partial view which I use in both Create and Edit views, called _ClientForm. In this view I have Contact1 and Contact2 and related properties in my model. Now, I'd like to create a common look for both of them and display side by side. Also, they both have Phone/Ext properties and I'd like some sort of visual control to be able to re-use it every time I have these two properties in my model.
I am not clear as what I should use and how should I go with the implementation.
Just to make it clear as what I mean.
Right now I have the partial view with the following code
#using WebDemo.Helper
#model CardNumbers.Objects.Client
<fieldset>
<legend>Client Info</legend>
#Html.ValidationSummary(true)
<input type="hidden" id="fntype" name="fntype">
#Html.HiddenFor(model => model.Id)
#Html.EditorFor(model => model.Number, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Name, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Address, EditorTemplate.EditBox)
<div id="ContactsInfo">
#*Contact 1*#
<div id="Contact1">
#Html.EditorFor(model => model.Contact1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Email1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Phone1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Ext1, EditorTemplate.TextBox)
</div>
#*Contact2*#
<div id="Contact2">
#Html.EditorFor(model => model.Contact2, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Email2, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Phone2, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Ext2, EditorTemplate.TextBox)
</div>
</div>
#*<div class="clear"></div>*#
<div id="SaveCancel" class="float-right">
<button type="Submit" id="btnSave">Save</button>
<button type="reset" id="btnCancel">Cancel</button>
</div>
</fieldset>
The view code is already a bit simplified using the technique described here
http://dotnetspeak.com/index.php/2012/10/asp-net-mvc-template-and-knockout-js
So, as you see I have 2 divs with the Contact information and inside each div I also have Phone/Ext with I'd like to place close to each other.
So, I am thinking I need something reusable for both: the Contact Info and phone/ext.
I also show my Client class for some further clarifications:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using DataAnnotationsExtensions;
using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic;
namespace CardNumbers.Objects
{
public class Client
{
//public Client()
//{
// this.ClientOrders = new List<ClientOrder>();
// this.Reorders = new List<Reorder>();
//}
[Key]
[Column("ClientId",TypeName = "int")]
public virtual int Id { get; set; }
[Required]
[DisplayName("Client No")]
[Column("client_no", TypeName = "smallint")]
public virtual Int16 Number { get; set; }
[Required]
[Column("client_name", TypeName = "varchar")]
[DisplayName("Client Name")]
[MaxLength(30, ErrorMessage = "Client Name should not be longer than 30 characters" )]
[MinLength(3, ErrorMessage = "Client Name is too short")]
public virtual string Name { get; set; }
[StringLength(100)]
[DisplayName("First Contact")]
[DisplayFormat(NullDisplayText = "")]
[Column("Contact1",TypeName = "varchar")]
public virtual string Contact1 { get; set; }
[Email]
[StringLength(100)]
[Column("c1_email", TypeName = "varchar")]
public virtual string Email1 { get; set; }
[DataType(DataType.PhoneNumber)]
[Column("C1_Phone", TypeName = "varchar")]
[StringLength(10)]
[DisplayName("Phone")]
public virtual string Phone1 { get; set; }
[StringLength(5)]
[Column("C1_Ext", TypeName = "varchar")]
[DisplayName("Ext")]
public virtual string Ext1 { get; set; }
[StringLength(100)]
[DisplayName("Second Contact")]
[Column("Contact2", TypeName = "varchar")]
public virtual string Contact2 { get; set; }
[Email]
[StringLength(100)]
[Column("C2_Email", TypeName = "varchar")]
public virtual string Email2 { get; set; }
[DataType(DataType.PhoneNumber)]
[StringLength(10)]
[DisplayName("Phone")]
[Column("C2_Phone", TypeName = "varchar")]
public virtual string Phone2 { get; set; }
[StringLength(5)]
[DisplayName("Ext")]
[Column("C2_Ext",TypeName = "varchar")]
public virtual string Ext2 { get; set; }
[DataType(DataType.MultilineText)]
public virtual string Address { get; set; }
[ForeignKey("EnteredByOperator")]
public string EnteredBy { get; set; }
[InverseProperty("ClientsEnteredBy")]
public virtual Operator EnteredByOperator { get; set; }
[ForeignKey("ModifiedByOperator")]
public string ModifiedBy { get; set; }
[InverseProperty("ClientsUpdatedBy")]
public virtual Operator ModifiedByOperator { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Created on")]
public DateTime EnteredOn { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Modified on")]
public DateTime? ModifiedOn { get; set; }
public virtual ICollection<ClientOrder> ClientOrders { get; set; }
public virtual ICollection<Reorder> Reorders { get; set; }
}
}`
`
Thanks a lot in advance.
I would add 2 EditorFor templates.
One that edits an individual contact info
One that is either for a list of contact info or for a special viewmodel that contains two contact infos. This template would in turn call editor for on all the contained contact info view models which would render the first template.
ViewModels
public class ContactDetails
{
public string Name {get;set;]
public string Email {get; set;}
}
public class ContactsInfo
{
public ContactDetails Contact1 {get; set; }
public ContactDetails Contact2 {get; set; }
}
public class Client {
public ContactsInfo ContactsInfo {get; set;}
}
Main View
#model client
...other html....
#Html.EditorFor(m => m.ContactsInfo)
...other html....
Editor Template ContactsInfo.cshtml
#model ContactsInfo
<div id="ContactsInfo">
<div id="Contact1">
#Html.EditorFor(m => m.Contact1)
</div>
<div id="Contact2">
#Html.EditorFor(m => m.Contact2)
</div>
</div>
Editor Template ContactDetails.cshtml
#model ContactDetails
#Html.EditorFor(model => model.Contact1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Email1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Phone1, EditorTemplate.TextBox)
#Html.EditorFor(model => model.Ext1, EditorTemplate.TextBox)

Binding SelectedItem from dropdownlist to model object in MVC 4

I'm very new with MVC, so bear with me, but I can't seem to bind a value from a SelectList to an instance of the selected object during a postback in MVC 4.
Suppose I have to create a Teacher as a member of a School. I have a ViewModel class defined as such:
public class RegisterTeacherModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[Display(Name = "School")]
public School SelectedSchool { get; set; }
[ScaffoldColumn(false)]
public Guid UserId
{
get;
set;
}
public SelectList PossibleSchools
{
get;
private set;
}
public RegisterTeacherModel(IRepository<School> schoolRepo)
{
PossibleSchools = new SelectList(schoolRepo, "Id", "Name");
}
}
And my View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>RegisterTeacherModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SelectedSchool)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedSchool, Model.PossibleSchools)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And finally, my Controller method:
[HttpPost, ActionName("Create")]
public ActionResult CreateTeacher(RegisterTeacherModel teacherModel)
{
if (ModelState.IsValid)
{
try
{
...
}
}
}
But when I receive the RegisterTeacherModel object back in my Create method in the Controller, SelectedSchool is always null. I must be missing something in the way the model binder re-creates the object references on postback. Can anyone point me in the right direction?
I think you touched on it with your second post: Try pointing the initial code to Model.SelectedSchool.<IdProperty>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedSchool.**<IdProperty>**, Model.PossibleSchools)
</div>
Well, I found a workaround. I still don't know if I'm missing something, but instead of using a School object in my ViewModel, I replaced it with the SelectedSchoolId as such:
public class RegisterTeacherModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[Display(Name = "School")]
public int SelectedSchoolId { get; set; }
...
}
And change my View dropdown to use this instead:
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedSchoolId, Model.PossibleSchools)
</div>
And then in my controller, when creating the real model objects I can simply pull the School object from the School repository and associate it with the real Teacher object.

Resources