I am creating a scheduling MVC app and I have 3 CodeFirst EF6 classes in a many-to-many configuration with the middle table containing additional information, such as time, date etc. of the meeting between the host and their visitors. I have created a ViewModel to allow me to create hosts, visitors and meetings on a single page instead of having to go to each page separately to create the required resources for the meeting. The controller and view for this arrangement are generating some questions.
I am passing, using ViewBag, a SelectList to the view
ViewBag.HostID = new SelectList(db.Hosts.OrderBy(x => x.Name), "id", "Name");
and
ViewBag.VisitorID = new SelectList(db.Visitors.OrderBy(x => x.LastName).
ThenBy(y => y.FirstName), "id", "VisitorName");
which is being successfully rendered in my Razor view using
<div class="form-group">
@Html.LabelFor(model => model.HostID, "HostID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("HostID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.HostID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.VisitorID, "VisitorID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("VisitorID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.VisitorID, "", new { @class = "text-danger" })
</div>
</div>
However, I'd like to be able to select a row in the DropDownList that has no associated HostID or VisitorID such that I can then enter a new Host or Visitor and have my controller create the necessary records when the form is posted back.
Therefore, my question is how do I add a non-database field to the top of the SelectList which will signify to the controller (once posted back) that a new record should be created instead of a reference to an existing Host be used?