I am building a simple ASP.NET MVC app with Entity Framework Database First that allows a user to edit tables in a database. One table has a foreign key to another table. I want the user to be able to change the foreign key value.
My question: How do I choose which column from the "foreign" table is displayed to the user in the view? I scaffolded the view out, but it is displaying the wrong column.
The foreign key is in the DealerAuto table, which has columns: DealerAutoID, DealerID, DealerMakeName, DealerModelName. For some reason, the dropdown in the view for DealerAutoID is pulling in DealerMakeName. I want it to pull in DealerModelName.
View.cshtml:
@model ModelYearChange.Models.DealerAutoTrim
[...]
<div class="form-group">
@Html.LabelFor(model => model.DealerAutoID, "DealerAutoID", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DealerAutoID", String.Empty)
@Html.ValidationMessageFor(model => model.DealerAutoID)
</div>
</div>
DealerAutoTrimController.cs:
public ActionResult Create()
{
ViewBag.DealerAutoID = new SelectList(db.DealerAutoes, "DealerAutoID", "DealerMakeName");
ViewBag.DealerModelName = new SelectList(db.DealerAutoes, "DealerModelName", "DealerModelName");
return View();
}
// POST: /DealerAutoTrim/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "DealerAutoTrimID,DealerAutoID,DealerTrimName,DealerTrimMSRP,DealerTrimMPG_City,DealerTrimMPG_Highway,DealerTrimBulletPoints,Year")] DealerAutoTrim dealerautotrim)
{
if (ModelState.IsValid)
{
db.DealerAutoTrims.Add(dealerautotrim);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DealerAutoID = new SelectList(db.DealerAutoes, "DealerAutoID", "DealerMakeName", dealerautotrim.DealerAutoID);
return View(dealerautotrim);
}