【发布时间】:2019-06-01 18:27:31
【问题描述】:
我有控制器名称 emp 有操作添加
我需要在动作添加视图加载时显示最后一个值加一
employeeid 文本框。
意思是假设我在员工表中的employeeid值为1,那么当添加操作时
查看加载的employeeid必须有2个。
那请问该怎么做呢?
在行动中我写什么
[httpget] 隐藏复制代码 公共 IActionResult 创建() { 我在这里写的 } 在视图中添加 我在这里写的
<div class="form-group">
<label asp-for="EmployeeId" class="control-label"></label>
<input asp-for="EmployeeId" class="form-control" />
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
我尝试过的:
var results = _context.GetAll().Where(Employee => Employee.EmployeeId> Employee.EmployeeId).OrderBy(Employee => Employee.EmployeeId).FirstOrDefault();
我将模型传递给视图
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmployeeId" class="control-label"></label>
<input asp-for="EmployeeId" class="form-control" />
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BranchCode" class="control-label"></label>
<input asp-for="BranchCode" class="form-control" />
<span asp-validation-for="BranchCode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeName" class="control-label"></label>
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeAge" class="control-label"></label>
<input asp-for="EmployeeAge" class="form-control" />
<span asp-validation-for="EmployeeAge" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoinDate" class="control-label"></label>
<input asp-for="JoinDate" class="form-control" />
<span asp-validation-for="JoinDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDate" class="control-label"></label>
<input asp-for="BirthDate" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="Active" /> @Html.DisplayNameFor(model => model.Active)
</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
【问题讨论】:
-
你为什么需要这个?我有一种感觉,你应该依靠数据库为你生成下一个 ID 值。英孚会这样做。
-
你能告诉我怎么做吗
-
你能告诉我怎么做吗
-
当你的实体有一个主键时,EF在你保存新记录时不会为你做吗?
-
这不是明智之举,因为您的数据库通常会在插入记录期间处理此问题。如果您生成 id,当您的视图加载时,另一个用户也会这样做并在您之前插入,当您点击提交时,该 ID 将已经存在,因此很可能引发异常。
标签: asp.net-mvc entity-framework model-view-controller