如何使用当前登录的用户自动填充DDL

时间:2016-07-29 16:46:34

标签: c# asp.net-mvc razor

我需要下拉列表来获取当前登录的用户,并在访问创建页面时自动使该用户成为列表中的所选项目。我将在剃刀页面上将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>

1 个答案:

答案 0 :(得分:0)

您可以将DropDownListFor辅助方法与强类型视图模型一起使用。

public class CreateVm
{
  public IEnumerable<SelectListItem> Users {set;get;}
  public int SelectedUserId {set;get;}
  public DateTime ClockIn {set;get;}
  public DateTimeClockout {set;get;}
}

并在您的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。将其替换为您当前的用户ID(我不知道您是如何存储的)。

并在您的视图中强烈输入此视图模型

@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");      
}