【发布时间】:2022-01-05 05:14:15
【问题描述】:
为简单起见,我将只包括模型的相关属性和相关行:
型号:Department.cs
属性:public virtual Staff HOD { get; set; }
控制器方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Add([Bind] Department newDepartment)
{
await _departmentRepository.AddDepartmentAsync(newDepartment);
await _departmentRepository.SaveTransactionAsync(true);
return Redirect("Details" + "/" + newDepartment.Id);
}
查看:
@model Department
@inject IStaffRepository staffRepository
@{
// select list
var listOfEmployees = new List<Staff>();
foreach (var staff in await staffRepository.GetAllStaffAsync())
{
listOfEmployees.Add(staff);
}
var selectListHOD = new SelectList(listOfEmployees, "EmployeeId", "Name"); //populates the option element with the correct Employee Id
}
<form class="form-group" method="post">
<div class="d-flex flex-column">
<div class="input-group" style="margin-bottom: 1%">
@Html.DropDownListFor(department => department.HOD, selectListHOD, htmlAttributes: new { @class="form-control" })
</div>
<div class="input-group">
<input class="btn btn-primary" type="submit" value="Save" />
</div>
</div>
</form>
结果:
(我没有在问题中包含此处看到的其他属性,但请相信我,控制器参数的属性会正确填充它们,HOD 属性除外)
来源:
<form class="form-group" method="post">
<div class="d-flex flex-column">
<div class="input-group" style="margin-bottom: 1%">
<input class="form-control" id="Id" name="Id" placeholder="Id" type="text" value="" /> </div>
<div class="input-group" style="margin-bottom: 1%">
<input class="form-control" id="Name" name="Name" placeholder="Department" type="text" value="" /> </div>
<div class="input-group" style="margin-bottom: 1%">
<input class="form-control" id="Description" name="Description" placeholder="Description" type="text" value="" /> </div>
<div class="input-group" style="margin-bottom: 1%">
<select class="form-control" id="HOD" name="HOD">
<option value="EMP01">Employee 1</option>
<option value="EMP02">Employee 2</option>
</select>
</div>
<div class="input-group">
<input class="btn btn-primary" type="submit" value="Save" /> </div>
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8AIwSWkSO0hJqMxy-oQKoeG35LTDmI2N1XHDZL9qeaxRxc17TyZbT2z9Iq0GMPkRyE7HnaX1r4ZSIs0bQATYB7w_A_HZDBXGETMmpdSqlMXZCmf7cH9ECzrNGz0Wuu9zHkE50yI92vPY-GxNPG-pRhs" />
</form>
我的猜测是提供给控制器的值似乎是错误的。我将如何传递实际对象而不是 ID?
我尝试使用this 代替EmployeeId,但它会抛出Object Reference not found 异常。
【问题讨论】:
-
简答;如果您没有每个属性的 html 输入/选择,则不会绑定任何值。恕我直言,我更喜欢
asp-for的标签助手而不是Html.DropDownListFor...docs.microsoft.com/en-us/aspnet/core/mvc/views/…。
标签: c# forms object data-binding asp.net-core-mvc