Answer the question
In order to leave comments, you need to log in
How to set not the ID of the connected entity but the Name field in the Create/Update view?
Hello connoisseurs.
The bottom line is that there are models:
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public List<Person> Persons { get; set; }
}
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public int DepartmentID { get; set; }
public Department Department { get; set; }
}
public class DepartmentContext : DbContext
{
public DepartmentContext (DbContextOptions<DepartmentContext> options)
: base(options)
{
}
public DbSet<Department> Department { get; set; }
public DbSet<Person> Person { get; set; }
}
public IActionResult Create()
{
ViewData["DepartmentID"] = new SelectList(_context.Department, "DepartmentID", "DepartmentID");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PersonID,Name,DepartmentID")] Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["DepartmentID"] = new SelectList(_context.Department, "Name", "Name", person.DepartmentID);
return View(person);
}
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DepartmentID" class="control-label"></label>
<select asp-for="DepartmentID" class ="form-control" asp-items="ViewBag.DepartmentID"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
Answer the question
In order to leave comments, you need to log in
The SelectList constructor has the signature :
public SelectList (System.Collections.IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue);
new SelectList(_context.Department,
nameof(Department.DepartmentID),
nameof(Department.Name),
person.DepartmentID);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question