2

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!

1 Answer 1

3

I managed to fix it by doing the following:

<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, (SelectList)ViewBag.PeopleList, "--Select--", new { @class = "form-control"})
            <span asp-validation-for="PersonId" class="text-danger"></span>
        </div>
    </div>

I wasn't casting the ViewBag.PeopleList to a SelectList, changing the second parameter in my Html.DropDownList to (SelectList)ViewBag.PeopleList fixed the issue for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.