jquery - 在此代码中,如何将来自 URL 的 ID 与数据库中的 ID 进行比较,然后将数据显示到该特定 ID
问题描述
所以我在控制器中有这段代码,可以通过他的 id 查看特定员工的 vecation 列表
public JsonResult GetVacatioinList(int? Id)
{
db.Configuration.ProxyCreationEnabled = false;
List<Vacations> VList = db.Vacations.Include(c => c.VacationType).Select(x => new Vacations
{
EmployeesId = x.EmployeesId,
Id = x.Id,
VacationType = x.VacationType,
StartDate = x.StartDate,
EndDate = x.EndDate,
Duration = x.Duration
}).Where(x=> x.EmployeesId == Id).ToList();
return Json(VList, JsonRequestBehavior.AllowGet);
}
此按钮将在 URL 中显示特定员工的 ID
<a class='btn btn-warning' href='http://localhost:26868/Vacations/Index?id='" + EmployeesList[i].Id + "><span class='glyphicon glyphicon-list'></span></a>
现在我需要将来自 URL 的 ID 与该用户的数据库中的 ID 进行比较,如果两者都显示该员工的假期
我试过了,当我没有在控制器的 LINQ 语句中添加 where 条件但没有显示数据时,它显示了所有假期,这是我使用的 jquery 代码
<script>
$("#LoadingStatus").html("Loading....");
$.get("/Vacations/GetVacatioinList", null, DataBind);
function DataBind(VacatioinList) {
var SetData = $("#SetVacatioinList");
for (var i = 0; i < VacatioinList.length; i++) {
if (VacatioinList[i].EmployeesId = Id) {
var dateforstart = new Date(parseInt(VacatioinList[i].StartDate.substr(6)));
var startdate = "";
startdate += dateforstart.format("mmm d, yyyy");
var dateforend = new Date(parseInt(VacatioinList[i].EndDate.substr(6)));
var enddate = "";
enddate += dateforend.format("mmm d,yyyy");
var Data = "<tr class='row_" + VacatioinList[i].Id + "'>" +
"<td>" + VacatioinList[i].Id + "</td>" +
"<td>" + VacatioinList[i].VacationType.Name + "</td>" +
"<td>" + VacatioinList[i].Duration + "</td>" +
"<td>" + startdate + "</td>" +
"<td>" + enddate + "</td>" + "</tr>";
SetData.append(Data);
$("#LoadingStatus").html("");
}
}
}
关于如何修复它的任何建议或实施该问题的替代方法
解决方案
如果我理解正确,那么您编写的 js 代码位于:
http://localhost:26868/Vacations/Index?id=someId
例如:
http://localhost:26868/Vacations/Index?id=55
如果是这种情况,那么这行代码:
$.get("/Vacations/GetVacatioinList", null, DataBind);
正在调用“/Vacations/GetVacatioinList”操作而不传递 Id 参数。
您的 MVC Action 接收 0 作为 Id 值,因此您的数据库没有返回任何结果。
你需要:
- 确保您在查询字符串中确实有一个 id 值 (Vacations/Index?id=someId)
- 用 js 读取那个值(你可以使用这个辅助函数来获取它)
改变你的 $get 行
$.get("/Vacations/GetVacatioinList", { Id: getParameterByName('id') }, DataBind);
然后你可以删除
if (VacatioinList[i].EmployeesId = Id)
最后,为了改进 db 调用,将“Where”部分移到“Select”部分之前
db.Vacations.Include(c => c.VacationType)
.Where(x=> x.EmployeesId == Id)
.Select(x => new Vacations
{
EmployeesId = x.EmployeesId,
Id = x.Id,
VacationType = x.VacationType,
StartDate = x.StartDate,
EndDate = x.EndDate,
Duration = x.Duration
})
.ToList();
推荐阅读
- typescript - 带有打字稿的 EmotionJS 不会将主题类型传递给样式化组件中的道具
- vbscript - Windows 2016 服务器的登录问题,之前我可以使用 VB 编写的代码登录
- azure - “az network vnet peering create”导致“BadRequestError:无法解析请求”。
- javascript - React redux 搜索无法正常工作
- sql - 有没有办法“打破”程序?
- html - 如果在提交 jQuery 时选中单选
- javascript - 如何制作反应菜单 Discord.js
- java - 如何使用 Keycloak REST API 使用 SMS OTP 无密码身份验证登录?
- excel - 在使用转换为链接数据类型(股票)命令的行之后,我的 VBA 子例程停止运行
- python - 创建随机 DNA 序列并将其保存为 csv 文件