0
我有兩個視圖模型:創建下拉列表asp.net核心
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; }
}
在創建/編輯的寵物我想有一個下拉所有的人可供選擇的列表。這是我的寵物控制器:
\\ 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);
}
我試圖通過ViewBag做到這一點,做的視圖,例如以下內容:
@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>
在試圖這樣做,我得到以下錯誤:Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
任何幫助表示讚賞。謝謝!