2012-04-26 67 views
1

是否可以在MVC 3中的特定字段上設置授權?在特定的ASP .NET MVC 3字段上設置授權?

我最初的想法(和MSDN研究)表明[Authorize]標籤僅用於控制器級別的動作(創建,編輯,索引等)。我可以在控制器動作上做到這一點:

[Authorize(Roles = "RoleA,RoleB")] 
    public ActionResult Create() 
    {    
     return View(new Tracking()); 
    } 

這種情況是兩個角色(RoleA和RoleB)可以訪問'Edit'控制器。但是隻有RoleA可以改變第一個字段。另一個角色(B)只能查看該字段。

我願做這樣的事情在一個特定領域:

[Required] 
[Range(1, 99)] 
[Authorize(Roles = "RoleA")] 
public int Sequence { get; set; } 

UPDATE1:

多一點研究下來的StackOverflow兔子角色表明,我需要使用局部視圖。

所以,在我看來,我添加以下代碼:

<div> 
    @if (Context.User.IsInRole("RoleA")) 
    { 
     @Html.Partial("_SequenceEdit") 
    } 
    else 
    { 
     @Html.Partial("_SequenceView") 
    } 

</div> 

因此,如果用戶是RoleA他們得到的局部視圖,允許「序列」字段的編輯。否則,他們只能看到「序列」字段。

我的觀點只有部分觀點如下:

<div class="editor-label"> 
     @Html.LabelFor(model => model.Sequence) 
    </div> 
    <div class="editor-field"> 
     @Html.DisplayFor(model => model.Sequence) 
     @Html.HiddenFor(model => model.Sequence) 
     @Html.ValidationMessageFor(model => model.Sequence) 
    </div> 
+0

你試過了嗎? – 2012-04-26 16:14:33

+1

對不起,但你是什麼意思一個MVC 3領域?你的意思是設置[授權]的具體行動?或者你不希望RoleB能夠修改的某個局部變量(一個字段)? – mfanto 2012-04-26 16:15:38

+0

@JamieDixon - 我不確定在哪裏嘗試並放置它。我猜測它可能會出現在控制器中,但它是特定於視野的視圖/模型。 – 2012-04-26 16:15:55

回答

1

我看你已經找到了如何修改視圖以不顯示一個文本框用戶角色B.但是你還應該進行服務器端驗證,以確保只有角色A中的用戶才能編輯該字段。

[Authorize(Roles = "RoleA,RoleB")] 
[HttpPost] 
public ActionResult Edit(int trackingID, Tracking newTrackingObject) 
{ 
    // grab the current version of the tracking object from your data repo 
    var oldTrackingObject = trackingRepo.GetByID(trackingID); 

    // check if the user is in role A and edit the sequence number 
    if(Context.User.IsInRole("RoleA")) 
     oldTrackingObject.Sequence = newTrackingObject.Sequence; 

    // continue processing the new tracking object 

    // after all processing is done, persist the edited tracking object back to the repo 
    trackingRepo.Update(oldTrackingObject); 
    trackingRepo.SaveChanges(); 
} 

這將防止通過手動編輯隱藏的表單字段改變序列字段中的角色B中的用戶(例如,與螢火蟲或類似的工具。)