2012-12-17 74 views
0

在分鐘,任何用戶可以預訂一個假期AY僱員,如何防止用戶在改變ASP.NET其他用戶數據MVC

我已經加入[授權]到控制器,並@if(用戶.Identity.IsAuthenticated)

在佈局上這樣只有登錄的用戶才能查看頁面。但我怎麼能只讓用戶預訂他們自己的假期

東西就像如果loggedInUserID(這是在用戶創建時自動分配?)= currentPersoID,雖然這只是一個猜測,我會prob有將相同的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

這到底是怎麼回事?爲什麼你甚至創建'HolidayList模型'?由於PList4DD似乎是在使用之後設置的,因此我無法看到它在哪裏使用?如果我誤解,請告訴我! – KingCronus

回答

3

在你的控制,有HttpContext.User.Identity.Name

它會給你的人當前登錄的用戶名。也許這可能是一個開始的好地方?

+0

感謝您的回覆,iv編輯了我的原始msg以包含我的代碼,它仍然允許任何用戶爲任何員工預訂,有什麼建議?謝謝 – John

1

所以,你需要對用戶名或用戶ID添加額外的檢查:

我會假設你正在返回查看模式類型的員工。

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) 
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) 
} 
+0

感謝您的回覆,如果你看看我的原始msg發佈我的代碼,但沒有發生任何想法?謝謝 – John

+0

@John基於你的問題的更新,你不會消除控制哪些*允許*用戶選擇不同的用戶的能力?在我的示例中,我將用戶名作爲隱藏字段存儲在頁面上,然後在服務器端進行驗證,這樣用戶只能**爲自己創建預訂。沒有爲其他用戶創建預訂的概念。如果你確實需要管理者的這個概念,那麼你可以在你的視圖模型中傳入一個標誌,表明用戶*可以*選擇一個用戶,渲染下拉菜單並將該值傳遞迴你的帖子。 – James

相關問題