I have two view models:
public class PersonViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
public ICollection<PetViewModel> Pets { get; set; }
}
public class PetViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int PersonId { get; set; }
public PersonViewModel Person { get; set; }
}
When creating/editing a pet I want to have a drop down list of all the people to choose from. This is my pets controller:
\\ Other methods omitted for brevity
[HttpGet]
public IActionResult Create()
{
var people = _personService.AsQueryable().ToList();
ViewBag.PeopleList = new SelectList(people , "Id", "FirstName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Id,Name,PersonId")] PetViewModel vm)
{
if (!ModelState.IsValid) return View(vm);
var pet = _petService.Create(vm.Name, vm.PersonId);
return RedirectToAction("Details", pet);
}
I am trying to do it via ViewBag and doing the following in the view as such:
@model UI.ViewModels.PetViewModel
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Create a Pet</h4>
<div class="form-group">
<label asp-for="PersonId" class="col-md-2 control-label"></label>
<div class="col-md-10">
@Html.DropDownListFor(model => model.PersonId, ViewBag.PeopleList, "--Select--", new { @class = "form-control"})
<span asp-validation-for="PersonId" class="text-danger"></span>
</div>
</div>
</div>
</form>
Upon trying to do so I get the following error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
Any help is appreciated. Thanks!