如何使用当前登录的用户自动填充DDL
问题描述:
我需要下拉列表来接收当前登录的用户,并在他们访问创建页面时自动将该用户作为列表中的选定项目。我将在剃须刀页面上将DDL设置为禁用,以便用户无法为其他用户创建。如何使用当前登录的用户自动填充DDL
我试了几件事,但我没有运气。
// GET: TimeStamps/Create
[Authorize]
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "FullName");
return View();
}
// POST: TimeStamps/Create
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,UserId,ClockIn,ClockOut")] TimeStamps timeStamps)
{
if (ModelState.IsValid)
{
db.TimeStamps.Add(timeStamps);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "FullName", timeStamps.UserId);
return View(timeStamps);
}
@Html.LabelFor(model => model.UserId, "User", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("UserId", null, "Select...", htmlAttributes: new {@class = "form-control"})
@Html.DropDownListFor(m => m.UserId, (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })
</div>
答
您可以使用DropDownListFor
辅助方法,用一个强类型的视图模型。
public class CreateVm
{
public IEnumerable<SelectListItem> Users {set;get;}
public int SelectedUserId {set;get;}
public DateTime ClockIn {set;get;}
public DateTimeClockout {set;get;}
}
,并在你的获取动作,
public ActionResult Create()
{
var vm = new CreateVm();
vm.Users= db.Users.Select(f=>new SelectListItem { Value=f.Id.ToString(),
Text=f.FullName}).ToList();
vm.SelectedUserId= 1; // Set the value here
return View(vm);
}
我硬编码的价值1
被选中。用你当前的用户标识代替(我不知道你是如何存储的)。
,并在你看来这是强类型的这种视图模型
@model CreateVm
@using(Html.BeginForm())
{
// Your other fields also goes here
@Html.DropDownListFor(s=>s.SelectedUserId,Model.Users)
<input type="submit" />
}
现在,在您HttpPost行动,你可以使用相同的视图模型
[HttpPost]
public ActionResult Create(CreateVm model)
{
var e=new TimeStamp { UserId=model.SelectedUserId,
ClockIn=model.ClockIn, Clockout=model.Clockout };
db.TimeStamps.Add(e);
db.SaveChanges();
return RedirectToAction("Index");
}
有一点要记住的是,即使您禁用下拉菜单,用户也可以将您的SELECT元素的值设置为其他任何值。所以我强烈建议你在保存前再次在你的HttpPost操作方法中设置值。
[HttpPost]
public ActionResult Create(CreateVm model)
{
var e=new TimeStamp { ClockIn=model.ClockIn,Clockout=model.Clockout };
e.UserId = 1; // Replace here current user id;
db.TimeStamps.Add(e);
db.SaveChanges();
return RedirectToAction("Index");
}