最迟,任何用户都可以为您的员工预订假期,
我已将[授权]添加到控制器,并且@if(User.Identity.IsAuthenticated)
在布局中只有登录用户才能查看页面。但是我怎样才能让用户为自己预订假期
类似于loggedInUserID(这是在创建用户时自动分配的吗?)= currentPersoID,虽然这只是一个猜测而且我不得不将相同的loggedInUserID分配给personID。
编辑:
[HttpPost]
public ActionResult Create(Holiday holiday)
{
var holidays = db.Holidays.Include("Person");
HolidayList model = new HolidayList();
//run through person
foreach (Person person in model.PList4DD)
{
//if Logged in user = person name
if (HttpContext.User.Identity.Name == person.Name)
{
//allow
if (ModelState.IsValid)
{
db.Holidays.AddObject(holiday);
db.SaveChanges();
return RedirectToAction("Index");
}
}
else
{
return RedirectToAction("Index");
}
}
model.PList4DD = db.People.ToList();
model.HList4DD = db.Holidays.ToList();
ViewBag.Id = new SelectList(db.People, "Id", "Name", holiday.Id);
return View(holiday);
}
由于
答案 0 :(得分:3)
在您的控制器中,有HttpContext.User.Identity.Name
它会为您提供当前登录用户的用户名。也许这可能是一个好的起点?
答案 1 :(得分:1)
因此,您需要针对用户名或用户ID添加其他检查:
我认为您返回View的模型属于employee。
public class Employee
{
public int Id { get; set; }
public string UserName { get; set; }
}
public ActionResult Home(int id)
{
Employee model = // Get employee by id
return View(model);
}
然后在您的视图中,您可以检查用户名:
@model Employee
@if (User.Identity.IsAuthenticated && User.Identity.Name == model.UserName)
答案 2 :(得分:1)
假设您的视图仅通过限制操作进行调用,则添加[Authorize]
应该已足够,因此无需在视图中执行@if(User.Identity.IsAuthenticated)
,因为用户永远不应该访问它。
至于你的实际问题,我会为你的预订视图创建一个视图模型,其中包含当前用户的用户名(或id),为简单起见,请使用用户名,例如。
public class BookingViewModel
{
[HiddenInput]
public Guid Username { get; set; }
...
}
然后在您看来,当您尝试回发到服务器时,您可以验证预订是否有效,例如
[HttpPost]
public ActionResult CreateBooking(BookingViewModel bookingModel)
{
if (bookingModel.UserId == User.Identity.Name)
{
// proceed with booking
return View("BookingComplete", bookingModel);
}
else
{
// add model state error
}
return View(bookingModel)
}